1

It shows an error ,when try to run this

declare  @tableName VARCHAR(250)

select @tableName='['+SCHEMA_NAME(schema_id)+'].['+name+']'

FROM sys.tables
WHERE '['+SCHEMA_NAME(schema_id)+'].['+name+']'='[Management].[Table_1]'

print @tableName

TRUNCATE table @tableName

Incorrect syntax near '@tableName'.

1 Answer 1

4

That is correct. You cannot use variables to pass table names.

You can use dynamic SQL:

declare @sql nvarchar(max);
set @sql = replace('TRUNCATE table @tableName', '@tableName', @tableName);

exec sp_executesql @sql;

SQL statements are allowed to have parameters for constants, but not for identifiers. This is not only a SQL Server limitation, but a limitation in all (?) databases. Dynamic sql is often used for this purpose.

TSQL sp_executesql

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

1 Comment

@user1254579 . . . That is how SQL is defined. In the case of SQL Server, there is a conflict with a table variable and a table name. To be honest, if the variable were set at compile time, I don't see an issue with it -- but no database supports this.

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.