我有一个名为 master 的表,主键是 account_num。每个帐号都有一个 account_type(单个字符)。我需要执行以下操作:
- 查找类型为 A 或 B 的所有帐户。
- 将该帐号与交易发生时间的时间戳一起存储在名为 year_end_close 的新表中
- 将 master 中所有类型为 A 的帐户设置为 C,并将所有类型为 B 的帐户设置为 D
在 SQL 中处理这个问题的最佳方法是什么?while循环?案例陈述?光标?任何帮助表示赞赏。该表有大约 17,000 行。
您不需要使用光标/循环来执行此类操作。在编写 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;
你在寻找这样的东西吗?(将“PRINT”语句替换为您的实际 SQL 语句)
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