1

I am writing a query which need to append the database name dynamically.

The query gets values from a table (in another database) , and I would interested to know if there is a better approach/way.

So my query looks like following :

DECLARE @TagNames AS VARCHAR(MAX) --Probably this is not a Global variable
DECLARE @QUERY AS VARCHAR(MAX)

        SET @QUERY ='SELECT @TagNames = coalesce( @TagNames + '','','''') +    
                     fldTagName FROM '+ dbo.fnGetZiConfigValue('KEYNAME')+'.dbo.tblTags Where  
                     fldInterpolate = 1 AND fldUnitID = 13'

        EXEC (@QUERY)

When I execute this , I get an error,

Must declare the scalar variable "@TagNames".

1 Answer 1

5

It is for sure not a global variable. You have to "declare" it inside dynamic SQL and return outside just like you'd do this with stored procedure.

DECLARE @TagNames AS VARCHAR(MAX) --Probably this is not a Global variable
DECLARE @QUERY AS NVARCHAR(MAX)
    SET @QUERY = N'SELECT @TagNames = coalesce( @TagNames + '','','''') +    
                 fldTagName FROM '+ QUOTENAME(dbo.fnGetZiConfigValue('KEYNAME'))+'.dbo.tblTags Where  
                 fldInterpolate = 1 AND fldUnitID = 13'

exec sp_executesql @QUERY, N'@TagNames VARCHAR(MAX) OUTPUT', @TagNames OUTPUT

for sp_executesql dynamic sql and it's params declaration must be NVarchar.

Sign up to request clarification or add additional context in comments.

5 Comments

on exec sp_executesql , Getting error , Unclosed quotation mark after the character string '@TagNames VARCHAR(MAX) OUTPUT), @@TagNames OUTPUT, If I close with quotations exec sp_executesql @@QUERY, N'@@TagNames VARCHAR(MAX) OUTPUT), @@TagNames OUTPUT' the getting an error Incorrect syntax near ','.
My bad for @@ (double @) , SO is not letting me with single @
typo fixed (was ) instead of ').
Thanks , If you don't mind a followup question , How do I add an extra parameter to the query to substitute hardcoded fldUnitId value. I tried with exec sp_executesql '@QUERY, N'@IPSet VARCHAR(50),@TagNames VARCHAR(MAX) OUTPUT', '@TagNames OUTPUT, but getting this error , The formal parameter "@IPSet" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output.
Updated this and it's working , exec sp_executesql @QUERY, N'@IPSet VARCHAR(50),@TagNames VARCHAR(MAX) OUTPUT', '@IPSet,@TagNames OUTPUT

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.