Question

I'm trying to write a dynamic query that produces the same results as the following, but replaces the fixed tablename with a variable.

    SELECT *
    WHERE tableName = 'Table2A' 

works fine but

    DECLARE @tablename AS NVARCHAR(100)
    SET @tablename = N'Table2A'
    DECLARE @execquery AS NVARCHAR(MAX)
    SET @execquery = N'
       SELECT *
       WHERE tableName = ''' + QUOTENAME(@tablename) + N''''    

    EXECUTE sp_executesql @execquery

returns no records. What am I doing wrong?

Was it helpful?

Solution

Aside from the fact that your SQL statement is invalid, QUOTENAME() simply places brackets "[]" around the supplied variable. Replace the EXECUTE statement with a PRINT statement, and you'll get the following results:

DECLARE @tablename AS NVARCHAR(100)
    SET @tablename = N'Table2A'
    DECLARE @execquery AS NVARCHAR(MAX)
    SET @execquery = N'
       SELECT *
       WHERE tableName = ''' + QUOTENAME(@tablename) + N''''    
PRINT @execquery
    --EXECUTE sp_executesql @execquery

RESULTS:

   SELECT *
   WHERE tableName = '[Table2A]'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top