Sunday, February 26, 2012

DYNAMIC TSQL

Here is the sample query:

DECLARE @.TABLENAME NVARCHAR(50);

DECLARE @.COL NVARCHAR(50);

DECLARE @.VALUE NVARCHAR(50);

/*** THESE VARIABLES WERE ARE BEING DYNAMICALLY FEEDED THROUGH CURSOR***/

DECLARE @.SQL1 NVARCHAR(1000);

SET SQL1 = 'SELECT * FROM' + @.TABLENAME + ' WHERE' + @. COL + '=" + @.VALUE

EXECUTE sp_executesql @.SQL1

Now when I execute this SP it gives me error invalid colunm name. I figure out that its because of the variable @.VALUE. Eventually I found out that I need to single quote the value of this dynamically feeded variable @. VALUE

is there any way I can do this; give quotes to @.value like @. COL + '=" + ' @.VALUE'

Use the following query,

Code Snippet

DECLARE@.TABLENAME NVARCHAR(50);

DECLARE@.COL NVARCHAR(50);

DECLARE@.VALUE NVARCHAR(50);

DECLARE@.SQL1 NVARCHAR(1000);

DECLARE@.PARAM NVARCHAR(1000);

SET @.SQL1= N'SELECT * FROM ' + @.TABLENAME + N' WHERE ' + @.COL + N'=@.VALUE';

SET @.PARAM = N'@.Value as Nvarchar(50)';

EXECUTEsp_executesql @.SQL1, @.PARAM, @.VALUE

No comments:

Post a Comment