[英]Can I use parameters in a CREATE query?
Actually I have 2 questions, both in SQL Server. 其实我有2个问题,都在SQL Server中。
There's a query like "Create Table" but for Create columns? 有一个类似“创建表”的查询,但是要创建列吗? If it exist, please, how it is?
如果存在,请怎么样?
I need to use a "Create Table" but using parameters, but I don't know if that is possible. 我需要使用“创建表”,但要使用参数,但是我不知道是否可行。 For example:
例如:
@table_name string, @column_name1 int, @column_name2 int, @column_name3 int CREATE TABLE @table_name ( @column_name1, @column_name2, @column_name3 .... );
Obviously that's only what I have in mind and doesn't work. 显然,这只是我的想法,不起作用。 There is a right way to do it?
有正确的方法吗?
I appreciate your help! 我感谢您的帮助!
By creating a column probably you mean adding a column to an existing table, right? 创建列可能意味着将列添加到现有表中,对吗?
use ALTER TABLE for that 为此使用ALTER TABLE
ALTER TABLE TableName ADD newColumn datatype ALTER TABLE TableName ADD newColumn数据类型
More info https://msdn.microsoft.com/en-us/library/ms190273.aspx 更多信息https://msdn.microsoft.com/en-us/library/ms190273.aspx
For dynamically creating a table, try using sp_executesql function 若要动态创建表,请尝试使用sp_executesql函数
sp_executesql 'CREATE TABLE @table_name @column_name1 datatype1, @column_name2 datatype2, @column_name3 datatype3 )', N'@table_name varchar(100), @column_name1 varchar(100), @column_name2 varchar(100), @column_name3 varchar(100)', @table_name, @column_name1, @column_name2, @column_name3
More info here https://msdn.microsoft.com/en-us/library/ms188001.aspx 更多信息在这里https://msdn.microsoft.com/zh-cn/library/ms188001.aspx
For #1, use ALTER TABLE command. 对于#1,请使用ALTER TABLE命令。
For #2, how are you executing the query? 对于#2,您如何执行查询? You can create a string variable first with the complete command and table name as parameter and then execute the query.
您可以先使用完整的命令和表名作为参数创建一个字符串变量,然后执行查询。 Something like:
就像是:
declare @ CustomerID int
set @ CustomerID = 3262833
declare @sql nvarchar(1000)
set @sql = N'SELECT * FROM [dbo].[Customers] AS [tbCustomers] WITH (NOLOCK)
WHERE tbCustomers.ID = '+ + cast(@CustomerID as nvarchar(10))
exec (@sql)
CREATE PROCEDURE create_table
@table varchar(10),
@ID varchar(10),
@Name varchar(20)
AS
BEGIN
Declare @sql nvarchar(MAX)
SET NOCOUNT ON
Set @sql = 'CREATE TABLE '+@table+'('+@ID+' bigint NOT NULL,'+@Name+' varchar(25)) ON [PRIMARY]';
exec (@sql)
END
GO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.