为什么标量变量在游标内未声明?

时间:2017-11-17 08:07:15

标签: sql sql-server tsql procedure

我编写了一个代码片段,它应该读取映射表(BcwmWDConfig)并在旧数据库(Items)中插入/更新过时表(BCWM99)的值到另一个数据库中的较新表(WebDET99.dbo.Items)。

我收到的错误是我所声明的(至少我认为)变量未被声明。

DECLARE @v_bcwm_id INT = 0, 
        @v_wd_guid VARCHAR = '';

DECLARE bcwm_config_read_cursor CURSOR FOR
    SELECT c.id, c.guid 
    FROM BcwmWDConfig c 
    WHERE c.guid IS NOT NULL;


PRINT '----READING CONFIG----';

OPEN bcwm_config_read_cursor

FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----INSERTING ITEMS WITH PARENT GUID: '+@v_wd_guid+'----'

    INSERT INTO WebDET99.dbo.Items
        SELECT 
            i.Id, i.Text, 
            CAST(@v_wd_guid AS VARCHAR(50)), 
            CAST(i.Linked_Feld AS VARCHAR(50)), 
            i.Linked_Item, i.Order
        FROM
            BCWM99.dbo.Items i
        WHERE 
            i.Parent_Feld = @v_bcwm_id

    PRINT '----INSERTED ITEMS WITH PARENT GUID: '+@v_wd_guid+'-----'

    FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid
END

CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET @v_bcwm_id = 0, @v_wd_guid = '';

OPEN bcwm_config_read_cursor
FETCH NEXT FROM bcwm_config_read_cursor
INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----UPDATING ITEMS WITH LINKED FIELD: '+@v_wd_guid+'----'
    UPDATE WebDET99.dbo.Items i
        SET i.Linked_Feld = @v_wd_guid
        WHERE i.Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))
    PRINT '----UPDATED ITEMS WITH LINKED FIELD: '+@v_wd_guid+'-----'
    FETCH NEXT FROM bcwm_config_read_cursor
    INTO @v_bcwm_id, @v_wd_guid
END
CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET     @v_bcwm_id = 0, 
        @v_wd_guid = '';

为什么他们在游标内未声明?另外我很确定我的代码中有一些较小的语法错误,我不熟悉SQL Server,也许有人发现这个过程有一些其他问题。

1 个答案:

答案 0 :(得分:0)

您的代码在sysntactically不正确。

第一个错误:您不能使用Order(保留字)而不使用方括号:

SELECT 
    i.Id, i.Text, 
    CAST(@v_wd_guid AS VARCHAR(50)), 
    CAST(i.Linked_Feld AS VARCHAR(50)), 
    i.Linked_Item, i.[Order] -----------------------------square brackets!

第二个错误:

SET @v_bcwm_id = 0, @v_wd_guid = '';

应该是:

SET @v_bcwm_id = 0; set @v_wd_guid = ''; ------------the same in the last row

最后一个错误:摆脱" i":

UPDATE WebDET99.dbo.Items
SET Linked_Feld = @v_wd_guid
WHERE Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))

只有这样才能编译你的代码。