How to create a table within a stored procedure using an attribute for the name of the table?
That was a long Title but it says it all. I'm trying to make a procedure which creates a table. I want it to be possible to choose the name of the table by writing it in the parameter. I've cut down on some of my code so you can see my problem.
I got so far, but it doesn't work - any ideas?
go
create 开发者_C百科proc newUser
@username varchar
as
execute 'create table '@username'(
id int,
name varchar
)'
This code does the job using quotename to avoid SQL injection:
CREATE PROCEDURE newUser
@username NVARCHAR(1000)
AS
DECLARE @cmd NVARCHAR(1000)
SET @cmd=N'CREATE TABLE '+quotename(@username)+N'(id INT, name NVARCHAR(1000))';
EXEC (@cmd);
精彩评论