views:

37

answers:

2

I am writing a fairly simple SQL query in SQL 2005, but am running into an issue and can't figure out what is wrong.

For documentation purposes, the query has to be a dynamic sql

A snippet of my query is:

@RecCreatorID int
....
....
IF (@RRecCreatorID IS NOT NULL)
    Begin
        Set @strSQL = @strSQL + ' AND RecCreatorID = @RecCreatorID'
    End

However, when I run PRINT @strSQL, what I get is

And RecCreatorID = @RecCreatorID

How can I get the actual value of @RecCreatorID to be displayed?

+3  A: 
@RecCreatorID int
....
....
IF (@RRecCreatorID IS NOT NULL)
    Begin
        Set @strSQL = @strSQL + ' AND RecCreatorID =' +  cast(@RecCreatorID as varchar(50))
    End

another solution is to use sp_executesql to execute query

Pranay Rana
Why would I cast that as varchar if its an int in the proc ?
user279521
because @RecCreatorID is integer and @strSQL is varchar
Pranay Rana
Correct, but might lead to SQL injections. (Of course when @RecCreatorId is a string.)
treaschf
Incredible. Thanks for the answer !!
user279521
i think sp_exeuctesql is better to use over here but condition is constrain over here
Pranay Rana
as opposed to Execute(@strSQL) ?
user279521
+2  A: 

Use sp_executesql. That stored procedure will accept parameters which you can then use inside your dynamic SQL (parameter substitution). For example:

Set @strSQL = @strSQL + ' AND RecCreatorID = @RecCreatorID_PARAM'


exec sp_executesql @SQL,
N'@RecCreatorID_PARAM int',
@RecCreatorID_PARAM = @RecCreatorID

Although this doesn't do much for displaying purposes, it's still a better way of handling dynamic SQL than concatenation, imho.

Rob