T-SQL创建动态表和填充

时间:2013-09-12 21:13:46

标签: sql-server tsql

我是T-SQL的新手,可以使用我正在编写的脚本的一些帮助。该脚本的目的是创建动态表并使用相关数据填充它们。目前我得到一个模糊的错误,我猜是因为我错过了一些语法。脚本如下。我的想法是我将运行脚本一次来创建和加载这些表。此过程是数据迁移项目的一部分。这是我在“执行”脚本时收到的错误。任何提示或建议表示赞赏。提前谢谢。

ERROR

Msg 102, Level 15, State 1, Line 81
Incorrect syntax near 'getSFContactID'.

SCRIPT

USE mylocalDB;
GO
-- Declare variables to temporarily hold dynamic SQL scripts
DECLARE @V_SF_CONTACT_ID VARCHAR(18) = '', 
        @V_TABLESCRIPT NVARCHAR(MAX) = '',
        @V_INSERTSCRIPT NVARCHAR(MAX) = '',
-- Declare variables to temporarily hold query records
        @V_FIRST_NAME nvarchar(50) = '',
        @V_LAST_NAME nvarchar(50) = '',
        @V_COMPANY nvarchar(100) = '',
        @V_ADDRESS_1 nvarchar(50) = '',
        @V_ADDRESS_2 nvarchar(50) = '',
        @V_CITY nvarchar(50) = '',
        @V_STATE nvarchar(2) = '',
        @V_ZIP nvarchar(10) = '',
        @V_Phone nvarchar(20) = ''


DECLARE getSFContactID CURSOR
FOR SELECT distinct CONTACTSFID FROM xrefListContactToAccountKey


OPEN getSFContactID


FETCH NEXT FROM getSFContactID
INTO @V_SF_CONTACT_ID


WHILE @@FETCH_STATUS = 0
BEGIN

/******************************************************
        BEGIN CREATING DYNAMIC TABLES
*******************************************************/

SET @V_TABLESCRIPT = '';
SET @V_INSERTSCRIPT = '';

IF OBJECT_ID(@V_SF_CONTACT_ID, 'U') IS NOT NULL
BEGIN

    SET @V_TABLESCRIPT = 'CREATE TABLE [dbo].[' + @V_SF_CONTACT_ID + '](
        [Key] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
        [FIRST_NAME] [nvarchar](50) NOT NULL,
        [LAST_NAME] [nvarchar](50) NOT NULL,
        [COMPANY] [nvarchar](100) NOT NULL,
        [ADDRESS_1] [nvarchar](50) NOT NULL,
        [ADDRESS_2] [nvarchar](50) NOT NULL,
        [CITY] [nvarchar](50) NOT NULL,
        [STATE] [nvarchar](2) NOT NULL,
        [ZIP] [nvarchar](10) NOT NULL,
        [Phone] [nvarchar](20) NULL,
     CONSTRAINT [PK_' + @V_SF_CONTACT_ID + '] PRIMARY KEY NONCLUSTERED ([Key] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]';
    --PRINT @V_SF_CONTACT_ID
    EXEC (@V_TABLESCRIPT)

    BREAK

    SET @V_INSERTSCRIPT = 'INSERT INTO [dbo].[' + @V_SF_CONTACT_ID + ']
        Select      CL.FirstName as FIRST_NAME,
                    CL.LastName as LAST_NAME,
                    CL.COMPANY,
                    CL.Street as ADDRESS_1,
                    CL.Street2 as ADDRESS_2,
                    CL.CITY,
                    CL.[STATE],
                    CL.ZIP,
                    CL.Phone
                FROM    [dbo].[Contact] CL

                WHERE CONTACTSFID = ''' + @V_SF_CONTACT_ID + '';

    EXEC (@V_INSERTSCRIPT)

FETCH NEXT FROM getSFContactID INTO @V_SF_CONTACT_ID

END


CLOSE getSFContactID
DEALLOCATE getSFContactID 

1 个答案:

答案 0 :(得分:2)

您有BEGIN个语句(2)而不是END个语句(1)。其中一个(WHILEIF)未关闭,因此您需要添加END才能将其关闭。