Creating Table with Table Name 由派生到 Procedure 的参数定义
Creating Table with Table Name defined by a parameter derived into Procedure
我正在尝试 运行 创建 table 的过程,table 名称基于传递给该过程的参数。
这是程序,我已经创建了:
Create PROCEDURE [dbo].[Creating_Table]
@number varchar(8)
AS
CREATE TABLE CONCAT(table_name,@number) (
column1 int,
column2 int,
column3 int
);
GO
有这方面的有效实施吗?
动态SQL会帮助你。
动态创建表是一件有风险的事情。
Create PROCEDURE [dbo].[Creating_Table]
@number varchar(8)
AS
BEGIN
DECLARE @Query VARCHAR(1000),@TableName VARCHAR(100)
SELECT @TableName = 'Table_'+ @number
SELECT @Query = '
CREATE TABLE '+@TableName+' (
column1 int,
column2 int,
column3 int
);'
EXEC (@Query)
END
或者,您可以使用已重命名的固定 "template table"
CREATE PROCEDURE [dbo].[Creating_Table] @number VARCHAR(8)
AS
BEGIN
SET NOCOUNT ON;
IF @number IS NULL
BEGIN
RETURN;
END
DECLARE @tablename NVARCHAR(128) = 'table_name' + @number;
--table already exists, return
IF OBJECT_ID('dbo.' + @tablename) IS NOT NULL
BEGIN
RETURN;
END
--if template does not exist, create it
IF OBJECT_ID('dbo.template_table') IS NULL
BEGIN
CREATE TABLE dbo.template_table
(
column1 int,
column2 int,
column3 int
);
END
--rename template
EXEC sp_rename 'dbo.template_table', @tablename, N'OBJECT';
RETURN;
END
我正在尝试 运行 创建 table 的过程,table 名称基于传递给该过程的参数。
这是程序,我已经创建了:
Create PROCEDURE [dbo].[Creating_Table]
@number varchar(8)
AS
CREATE TABLE CONCAT(table_name,@number) (
column1 int,
column2 int,
column3 int
);
GO
有这方面的有效实施吗?
动态SQL会帮助你。
动态创建表是一件有风险的事情。
Create PROCEDURE [dbo].[Creating_Table]
@number varchar(8)
AS
BEGIN
DECLARE @Query VARCHAR(1000),@TableName VARCHAR(100)
SELECT @TableName = 'Table_'+ @number
SELECT @Query = '
CREATE TABLE '+@TableName+' (
column1 int,
column2 int,
column3 int
);'
EXEC (@Query)
END
或者,您可以使用已重命名的固定 "template table"
CREATE PROCEDURE [dbo].[Creating_Table] @number VARCHAR(8)
AS
BEGIN
SET NOCOUNT ON;
IF @number IS NULL
BEGIN
RETURN;
END
DECLARE @tablename NVARCHAR(128) = 'table_name' + @number;
--table already exists, return
IF OBJECT_ID('dbo.' + @tablename) IS NOT NULL
BEGIN
RETURN;
END
--if template does not exist, create it
IF OBJECT_ID('dbo.template_table') IS NULL
BEGIN
CREATE TABLE dbo.template_table
(
column1 int,
column2 int,
column3 int
);
END
--rename template
EXEC sp_rename 'dbo.template_table', @tablename, N'OBJECT';
RETURN;
END