Discussion Locked

SQL Server Stored Procedure

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

How can you place a variable in the TableName of a CREATE TABLE SQL Statement inside a stored procedure? Because just declaring a varchar doesn't seem to do the trick...

For instance;

DECLARE @MyTable varchar(20)

BEGIN
Code that puts string into @MyTable
END

BEGIN
Create Table @MyTable (blah blah)
END

Thanks,
-Parker

3 replies

by cheffero

Todd-
If the system stored procedure, sp_executesql, is available to you, you can use this in conjunction with the table name variable to accomplish the table creation. E.g., the following SQL should accomplish what you're looking to do:
----
DECLARE @MyTable varchar(20), @CreateStmnt nvarchar(128)

select @MyTable = 'NEW_TABLE'
select @CreateStmnt = 'create table ' + @MyTable + ' (col_a int, col_b varchar(255))'

EXEC sp_executesql @CreateStmnt
----

Hope this was helpful.

by shanghai sam

Cheffero,

Yes, that sp is available to me, and I was able to use it accordingly. It worked out like a champ once I realized I needed to extend the number of chars in that nvarchar to fit my statement. ;) Some things just come slowly to others...

But, that's exactly what I needed to know.

Thanks tons,
-Parker

This discussion is closed to new replies.