简体   繁体   中英

How to create a table with name as parameter?

I don't find in documentation on msdn, how to insert to execute statement a parameter of table name. By parity of reasoning I tried:

var myNameOfTable = "wantedName";
db.Execute("CREATE TABLE @0 (id int IDENTITY (1,1) PRIMARY KEY, data ntext, dataOfAdd datetime)", myNameOfTable);

But I get error:

[ Token line number = 1,Token line offset = 14,Token in error = @0 ]

Please help me - how to create table with name as parameter?

You are giving table name through options, instead using string concatenation/string.Format to make the query. You at least use Paramerized Query or better use stored procedure instead of inline query as they could result in sql injection . You can read this post Stored procedures vs. inline SQL for comparison.

db.Execute("CREATE TABLE " + myNameOfTable + " (id int IDENTITY (1,1) PRIMARY KEY, data ntext, dataOfAdd datetime)" );

The syntax you are using could be achieved using string.Format

db.Execute(string.Format("CREATE TABLE {0} (id int IDENTITY (1,1) PRIMARY KEY, data ntext, dataOfAdd datetime)", myNameOfTable));

I'd agree that I'd rather use legitimate parameters here. You could create a stored procedure that you pass in a table name to, something like this comes to mind:

CREATE PROCEDURE dbo.usp_CreateTable
    @TableName VARCHAR(50)
AS
BEGIN

    DECLARE @SqlScript NVARCHAR(4000)
    SET @SqlScript = 'CREATE TABLE ' + @TableName + ' (ID INT IDENTITY (1,1) NOT NULL)'

    EXEC sp_executesql @SqlScript

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM