M
M
Michael2016-01-10 18:56:28
SQL
Michael, 2016-01-10 18:56:28

How to create a stored procedure where the parameter will be the table name?

I'm trying to create a stored procedure in which the name of the created table is set as a parameter. Tried initially like this (because the name is a unique number):

CREATE PROCEDURE createTableFact
  (
    @name int
  )
AS
CREATE TABLE @name (id int not null IDENTITY (1,1), products varchar(max), weight int, boxes int, suma int, total int)

But it cursed at @name (Incorrect syntax near "@name". Expected ".", ID, or QOUTED_ID.)
Changed to this:
CREATE PROCEDURE createTableFact
  (
    @name varchar(max)
  )
AS
CREATE TABLE @name (id int not null IDENTITY (1,1), products varchar(max), weight int, boxes int, suma int, total int)

The problem hasn't been resolved.
I decided to create a table through an SQL query in the program itself (I write in c # using SqlConnection)
cmd.CommandText = "CREATE TABLE "+affected+" (id int not null IDENTITY (1,1), products varchar(max), weight int, boxes int, suma int, total int)";

Where affected is an int variable with that name and an assigned number.
In principle, he eats it, but returns an error where he does not like the number.
Tried to convert to String - same effect.
Already all the head broke how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kovalsky, 2016-01-10
@sqliteman

The idea smacks of insanity, so I want to learn more about the idea and business logic, why all this. And there is a
solution

P
Peter, 2016-01-10
@petermzg

You can create a query dynamically and execute it

DECLARE @sql NVARCHAR(max)=''
SELECT @sql = ' CREATE TABLE '[email protected] + ...
Exec Sp_executesql @sql

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question