我有一个名为master的表,主键是account_num。每个帐号都有一个account_type(单个字符)。我需要做以下事情:
在SQL中处理此问题的最佳方法是什么?循环?案例陈述?光标?任何帮助表示赞赏。该表有大约17,000行。
答案 0 :(得分:3)
您不需要使用游标/循环来执行此类操作。编写SQL时,总是先尝试寻找基于集合的解决方案。我建议使用CASE
语句,这是您提到的选项之一。
试试这个:
BEGIN TRAN;
SELECT account_num, CURRENT_TIMESTAMP
INTO year_end_close
FROM dbo.master
WHERE account_type IN ('a','b');
UPDATE dbo.master
SET account_type = CASE account_type
WHEN 'a' THEN 'c'
WHEN 'b' THEN 'd'
ELSE account_type
END
WHERE account_type IN ('a','b');
COMMIT TRAN;
答案 1 :(得分:2)
DECLARE @MasterTable TABLE
(
account_num int,
account_type varchar(1)
)
INSERT INTO @MasterTable VALUES (1, 'A')
INSERT INTO @MasterTable VALUES (2, 'A')
INSERT INTO @MasterTable VALUES (3, 'B')
INSERT INTO @MasterTable VALUES (4, 'B')
INSERT INTO @MasterTable VALUES (5, 'C')
INSERT INTO @MasterTable VALUES (6, 'C')
DECLARE @account_num int
DECLARE @account_type varchar(1)
DECLARE @switch_type varchar(1)
DECLARE db_cursor CURSOR FOR
SELECT account_num, account_type
FROM @MasterTable
WHERE account_type IN ('A', 'B')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @account_num, @account_type
WHILE @@FETCH_STATUS = 0
BEGIN
IF @account_type = 'A'
SET @switch_type = 'C'
ELSE
SET @switch_type = 'D'
PRINT 'INSERT year_end_close (account_num, timestampfield) VALUES (' + CAST(@account_num AS VARCHAR) + ', GETDATE())'
PRINT 'UPDATE @MasterTable SET account_type = ' + @switch_type + ' WHERE account_num = ' + CAST(@account_num AS VARCHAR)
FETCH NEXT FROM db_cursor INTO @account_num, @account_type
END
CLOSE db_cursor
DEALLOCATE db_cursor