使用IF语句更新行

时间:2016-12-09 19:57:18

标签: sql-server tsql

我在根据某些条件更新结果集时遇到了困难。某些帐号为空,但根据不同的标识符匹配。

我正在使用匹配的帐号更新空帐号,但无法使语法正常工作。我遇到了错误

  

无法找到多部分标识符“CMRR.aacount_number”

这是我引用另一张桌子的几个不同的地方。

DECLARE @BatchId INT
SET @BatchId = 1030

SELECT 
    CMRR.id,
    CMRR.account_number,
    CMRR.URN
FROM 
    CRA_METRO2_REJECTED_RECORDS AS CMRR
WHERE 
    batch_id = @BatchId

IF CMRR.account_number = ''
BEGIN
    UPDATE CRA_METRO2_REJECTED_RECORDS 
    SET CMRR.account_number = (SELECT account_number 
                               FROM CRA_METRO2_REJECTED_RECORDS
                               WHERE URN = CMRR.URN
                                  AND account_number != '')
    WHERE id = CMRR.id
END

1 个答案:

答案 0 :(得分:2)

我相信这可以满足您的需求。我添加了3个变量来保存select语句中的值。您将要检查数据类型,因为我刚刚使用^asd.com/cat/.* 而不知道它们在您的系统中是什么。然后在更新语句中使用这些变量。

INT

修改

经过简短的聊天,这就是解决方案。

DECLARE @BatchId INT

-- Added variables 
DECLARE @id INT
DECLARE @urn INT
DECLARE @account_number INT

SET @BatchId = 1030

-- Assign values to variables
SELECT 
    @id = id
  , @account_number = account_number
  , @urn = urn
FROM CRA_METRO2_REJECTED_RECORDS
WHERE batch_id = @BatchId


IF @account_number = ''
BEGIN
  UPDATE CRA_METRO2_REJECTED_RECORDS 
  SET account_number = (SELECT account_number 
                             FROM CRA_METRO2_REJECTED_RECORDS
                             WHERE URN = @URN
                             AND account_number != '')
  WHERE id = @id
END