0

My Dynamic SQL queries have been placed inside a table. I want to read these from the table (in SQL server), do a parameter substitution, then execute the dynamic query.

i.e. Column GetFieldServerSQL contains the following:

SELECT top 1 Tenancy.LeadName 
FROM Tenancy 
RIGHT OUTER JOIN Property ON Tenancy.KeyProperty = Property.KeyProperty 
WHERE (Tenancy.EndDate IS NULL) and Property.KeyProperty = @PropertyID

This is what I have tried:

declare @sql nvarchar(1000)
declare @sql2 nvarchar(1000)
declare @res nvarchar(1000)
declare @result nvarchar(1000)

set @sql = 'SELECT [GetFieldServerSQL]
FROM [SVSCentral].[dbo].[SVSSurvey_ExternalField] where ID=5'

exec @res = sys.sp_executesql @sql
print @res

This returns my query in the Results window, but I want it as a variable. @res only contains a 0 (for success)

Once I have it as a variable, I want to do a substitution. Something like:

set @sql2 = REPLACE(@result,'@propertyID','1003443')

(supposing @result is where my results is stored)

And then execute it:

exec (@sql2)

1 Answer 1

2

Instead of doing this:

exec @res = sys.sp_executesql @sql

You need to insert the results into a table, then select from that table, like this:

DECLARE @resTable TABLE (res nvarchar(1000))
INSERT INTO @resTable (res)
exec (@sql)

SELECT @res=res from @resTable
print @res
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.