UPDATE包装在游标中时出现SQL错误

时间:2014-07-06 18:01:07

标签: sql sql-server

以下代码本身完全符合我的要求。

UPDATE [MASKED_2014-06-30-2014-06-01-CUSTOMER325] 
SET    [MASKED_2014-06-30-2014-06-01-CUSTOMER325].[SELL PRICE] = ROUND 
([Orbisrates].[dbo].[ORBIS_IMPORT_JUNE2014].[PEAKPERMINUTE] / 60 * 
[OrbisBilling].[dbo].[MASKED_2014-06-30-2014-06-01-CUSTOMER325].[CHARGEDTIMESECS] + [Orbisrates].[dbo].[ORBIS_IMPORT_JUNE2014].[PEAKCONNECT], 4) 
FROM   [OrbisRates].[dbo].[ORBIS_IMPORT_JUNE2014] 
       INNER JOIN 
       [OrbisBilling].[dbo].[MASKED_2014-06-30-2014-06-01-CUSTOMER325] 
               ON 
       [OrbisBilling].[dbo].[MASKED_2014-06-30-2014-06-01-CUSTOMER325].[TO] 
       LIKE 
       [ORBIS_IMPORT_JUNE2014].[DESTINATION] + '%' 
WHERE 
[OrbisBilling].[dbo].[MASKED_2014-06-30-2014-06-01-CUSTOMER325].[TARIFF LOOKUP] 
= 'Orbis_Import_June2014' 

问题在于,当我将其包装在游标中时,我收到错误。

如果我将代码放入光标而没有任何编辑,如下所示,我得到

  

Msg 102,Level 15,State 1,Line 13
  ' Orbis_Import_June2014'

附近的语法不正确

代码:

DECLARE @tablevalue NVARCHAR(MAX), @sql NVARCHAR(MAX); 

DECLARE table_value_cursor CURSOR FOR
   SELECT DISTINCT [Tariff Lookup]
   FROM [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325];

OPEN table_value_cursor 

FETCH NEXT FROM table_value_cursor INTO @tablevalue 

WHILE @@FETCH_STATUS = 0 
BEGIN
    SELECT @sql = N'

    UPDATE [masked_2014-06-30-2014-06-01-customer325] 
    SET [masked_2014-06-30-2014-06-01-customer325].[Sell Price] = 
ROUND ([Orbisrates].[dbo].[Orbis_Import_June2014].[Peakperminute]/60*[OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[ChargedTimeSecs]+[Orbisrates].[dbo].[Orbis_Import_June2014].[Peakconnect],4) 
    FROM [OrbisRates].[dbo].[Orbis_Import_June2014]
    INNER JOIN [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325] on [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[To] LIKE [Orbis_Import_June2014].[Destination]+'%'
    WHERE [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[tariff lookup] = 'Orbis_Import_June2014'';

    EXEC sp_executesql @sql; 

    FETCH NEXT FROM table_value_cursor INTO @tablevalue; 
END 

CLOSE table_value_cursor 
DEALLOCATE table_value_cursor;

为了摆脱这个错误,我在WHERE语句中添加了几个引号。

WHERE [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[tariff lookup] = ''Orbis_Import_June2014'''

但是现在当我运行代码时出错了,说

  

数据类型nvarchar和varchar在模运算符中不兼容。

根据前一篇文章中的一些建议,我将LIKE声明放在其他引号中,但无济于事。同样的错误

INNER JOIN [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325] on [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[To] LIKE ''[Orbis_Import_June2014].[Destination]+'%'''

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果[资费查询]列的数据类型为NVarChar(),请在您的值之前使用N

WHERE [OrbisBilling].[dbo].[masked_2014-06-30-2014-06-01-customer325].[tariff lookup] = N''Orbis_Import_June2014'''