简体   繁体   English

如何创建一个名为参数的表?

[英]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. 我没有在msdn的文档中找到,如何插入执行语句表名的参数。 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 ] [令牌行号= 1,令牌行偏移= 14,令牌错误= @ 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. 您通过选项提供表名,而不是使用字符串连接/ string.Format来进行查询。 You at least use Paramerized Query or better use stored procedure instead of inline query as they could result in sql injection . 您至少使用Paramerized Query或更好地使用存储过程而不是内联查询,因为它们可能导致sql注入 You can read this post Stored procedures vs. inline SQL for comparison. 您可以阅读此帖子存储过程与内联SQL进行比较。

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 您正在使用的语法可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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