1

Is it possible to concatenate a sting to a variable as a table name.

e.g.

DECLARE @ENTITY VARCHAR(50)
SET @ENTITY = 'NATURAL'

SELECT * 
INTO @ENTITY+'_COMPLETENESS_NAME'
FROM TABLE1

As a result I would like to create a table, named [NATURAL_COMPLETENESS_NAME]

I am currently using MS SQL Server 2014

2 Answers 2

4

You need to use dynamic SQL:

DECLARE @sql NVARCHAR(max);

SET @sql = '
SELECT * 
INTO ' + @ENTITY + '_COMPLETENESS_NAME
FROM TABLE1';

EXEC sp_executesql @sql;

Note: You cannot use a parameter for the table name, because you can't use parameters for table, column, schema, or database identifiers. To be safe, you might want to use:

SET @sql = '
SELECT * 
INTO ' + QUOTENAME(@ENTITY + '_COMPLETENESS_NAME') +
FROM TABLE1';

This protects you if @ENTITY has unusual characters.

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

Comments

2

Try This:

DECLARE @ENTITY VARCHAR(50)
SET @ENTITY = 'NATURAL'

EXEC ('SELECT  * INTO '+ @ENTITY + '_COMPLETENESS_NAME FROM TABLE1')

Comments

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.