Question

I'm getting an incorrect syntax near 'dtproperties'. It works perfectly fine if I don't have it as a dynamic sql. But why isn't it working if it's in a dynamic sql? My assignment requires me to use the dynamic sql.

USE MyGuitarShop;
DECLARE @DynamicSQL varchar(8000);

SET @DynamicSQL =
 'SELECT TOP 1 sys.tables.name, COUNT(*) AS TotalTable
 FROM sys.tables
 WHERE sys.tables.name NOT IN ('dtproperties', 'sysdiagrams')
 GROUP BY sys.tables.name
 ORDER BY sys.tables.name';

EXEC (@DynamicSQL);
Was it helpful?

Solution

double the single quote to escape a single quote.

SET @DynamicSQL =
 'SELECT TOP 1 sys.tables.name, COUNT(*) AS TotalTable
 FROM sys.tables
 WHERE sys.tables.name NOT IN (''dtproperties'', ''sysdiagrams'')
 GROUP BY sys.tables.name
 ORDER BY sys.tables.name';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top