Sql-Server-2008

儲存過程從具有變數約束的變數創建表

  • May 7, 2020

我已經設法使用儲存過程來創建具有變數名的表的副本。但我很難理解如何將約束合併到儲存過程中。

問題:約束必須是一個變數,因為當它複製一個表時,它不能命名我擁有的 PK 與以前使用的相同。我在這些區域遇到語法錯誤。

我對 SQL Server 很陌生…今天才剛剛開始學習!!所以請用虛擬術語解釋。

到目前為止的程式碼如下:

   CREATE PROCEDURE procFinancialPeriodTable
       (@TABLENAME as varchar (50))
   AS
       DECLARE @SQL varchar(2000)
       --SET @SQL = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[@TABLENAME]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
       --drop table [dbo].[@TABLENAME]
   BEGIN
       SELECT @SQL = 'CREATE TABLE ' + @TABLENAME + '('

       SELECT @SQL = @SQL + '[ID] [int] IDENTITY(1,1) NOT NULL,[FinPeriodNr] [int] NOT NULL,[FinCurrentPeriod] [bit] NULL,[FinStart] [date] NULL,[FinEnd] [date] NULL,[FinStatusOpen] [bit] NOT NULL,[PeriodClosedTS] [smalldatetime] NULL,[PeriodClosedUID] [varchar](3) NULL,)'
   CONSTRAINT [PK_FinancialPeriod' + @TABLENAME + '_1] PRIMARY KEY CLUSTERED(
   [FinPeriodNr] ASC
   )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,                 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
   ) ON [PRIMARY]

   EXEC(@SQL)

   SET NOCOUNT ON;
END

您的邏輯似乎很好,您收到語法錯誤,因為您沒有正確分隔字元串。

[PeriodClosedUID] [varchar](3) NULL,)' <-- problem

此外,輸入和縮進的自由也是非常有幫助的,所以像這樣的問題不會隱藏 4 個螢幕,只能通過水平捲動條訪問。

CREATE PROCEDURE dbo.procFinancialPeriodTable -- always use schema prefix
   @TABLENAME SYSNAME
AS
BEGIN -- use body wrappers around whole body
 SET NOCOUNT ON; -- put this at the beginning - no point in setting it at the end

 DECLARE @SQL NVARCHAR(MAX); -- dynamic SQL should always be Unicode

 SELECT @SQL = 'CREATE TABLE dbo.' + QUOTENAME(@TABLENAME) + '('
   + '[ID] [int] IDENTITY(1,1) NOT NULL,[FinPeriodNr] [int] NOT NULL,
      [FinCurrentPeriod] [bit] NULL,[FinStart] [date] NULL,
      [FinEnd] [date] NULL,[FinStatusOpen] [bit] NOT NULL,
      [PeriodClosedTS] [smalldatetime] NULL,[PeriodClosedUID] [varchar](3) NULL,
      CONSTRAINT [PK_FinancialPeriod_' + @TABLENAME + '_1] PRIMARY KEY CLUSTERED(
        [FinPeriodNr]));'; -- all those options you specified were verbose defaults

 EXEC sp_executesql @sql; -- instead of EXEC(@sql)
END
GO

一些連結:

引用自:https://dba.stackexchange.com/questions/39249