0

I want to create dynamic name for my database tables. I declare variable and use it as my table name.

ERROR: Incorrect syntax near '@sample'. Expecting '.',ID or QUOTED_ID

CREATE PROCEDURE [dbo].[sp_SAMPLE]
    @name nvarchar(50)
AS
BEGIN

SET NOCOUNT ON;

DECLARE @sample nvarchar(50);
SET @sample = 'tbl_function_' + @name;

Create Table @sample
(
    id int not null,
    UserType nvarchar(50) null,
    paramater2 nvarchar(50) null
)
END

Is there any way to make my table name dynamic? Thank you.

2 Answers 2

2

I'm not sure why you would want to do this. But, you can do it using dynamic SQL:

CREATE PROCEDURE [dbo].[sp_SAMPLE]
    @name nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sql nvarchar(max);

    SET @sql = '
Create Table tbl_function_@name
(
    id int not null,
    UserType nvarchar(50) null,
    paramater2 nvarchar(50) null
)';

    SET @sql = REPLACE(@sql, '@name', @name);

    EXEC sp_executesql @sql;
END;

Why would you want to create a separate table for each @name, instead of just inserting rows with @name in a column?

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

1 Comment

Thank you it works now. Also thank you for your idea adding column @name to my table.
0
CREATE PROCEDURE [dbo].[sp_SAMPLE]
@name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON

DECLARE @sql varchar(4000);

SET @sql = '
Create Table tbl_function_'+@name+'
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)'

EXEC (@sql) 
END

2 Comments

some comments would be nice, otherwise it's just a code-dump
@Ted this is another way to get results not a code-dump

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.