Suppose I want to select a constant value in an sql query, I could do something like this :
select name,age,'tick' from tableA
I want to dynamically generating an sql query using stored procedures. For example :
SELECT @SQL = 'SELECT CID,DOB, NAME, '+@Scname+' from ' + @TableName
Where @TableName, @Scname are dynamically generated variables in a while loop. Here @Scname is interpreted as a column name instead of a constant string when executing query on @TableName. I have tried using escape characters as follows :
SELECT @SQL = 'SELECT CID,DOB, NAME, "'+@Scname+'" from ' + @TableName
But it returns a floating point value full of zeros instead of the string contained in @Scname.
Advertisement
Answer
I think following should work
SET @SQL = 'SELECT CID,DOB, NAME,'+''''+@Scname+''''+' from '+ @TableName