0

Looking for way to create some dynamic SQL to drop a table if it exists. However I can not seem to get the syntax correct. Here is the query so far (renamed fields for security)

DECLARE @TableNameNew NVARCHAR(MAX)
DECLARE @DynamicSQL2 NVARCHAR(MAX)

SET @TableNameNew = (SELECT  'tbl1_' + REPLACE(StaffCode,'.','') AS TableName
         FROM tblEmployee WHERE (PCLogin = REPLACE(SYSTEM_USER, 'DOMAIN\', '')))
SET @DynamicSQL2 = 'IF OBJECT_ID(' + '''' + @TableNameNew + '''' + +','+'''U''' + ') IS NOT NULL DROP TABLE ' + @TableNameNew

EXEC @DynamicSQL2

This returns an error:

Could not find stored procedure 'IF OBJECT_ID('tbl1_ghewitt','U') IS NOT NULL DROP TABLE tbl1_ghewitt'.

1 Answer 1

2

Try

EXECUTE sp_executesql @DynamicSQL2

instead of

EXEC @DynamicSQL2
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.