sqlsql-serversql-server-2017sp-executesql

EXEC sp_executesql will work with Integers but not VarChars


I'm using EXEC sp_executesql for a dynamic query in SQL Server 2017.

I've tried various testing scenarios, and I can get results in my query (for other parameters) as long as the values passed in are Integers. So, that means, Location and Department testing works. However, I can't figure out if there's something I need to do differently for when I'm sending a NVARCHAR or DateTime.

Here's my stored procedure, with the NVARCHAR param. Do you see anything I'm doing wrong?


(
@tktitle NVARCHAR(200)
)

AS
BEGIN

Declare  @SQL NVARCHAR(MAX)

Set @SQL = 'SELECT        timekeep.tkinit, timekeep.tkfirst, timekeep.tklast, 
                         timekeep.tkemdate, timekeep.tktitle, timekeep.tkloc, timekeep.tkdept

FROM   abc.xyz'        
                     


IF @tktitle IS NOT NULL
Select @SQL = @SQL + 'AND ([tktitle] = @tktitle)'
EXEC sp_executesql @SQL, N'@tktitle varchar',  @tktitle


END

Solution

  • I can identify at least three issues:

    So:

    IF @tktitle IS NOT NULL
        Select @SQL = @SQL + ' WHERE ([tktitle] = @tktitle)';
    -------------------------^ separator
    EXEC sp_executesql @SQL, N'@tktitle varchar(200)', @tktitle=@tktitle;