简体   繁体   English

SQL遍历表中的记录

[英]SQL Loop through records in a table

I have a table called master, the primary key is account_num. 我有一个名为master的表,主键是account_num。 Each account number has an account_type (single character). 每个帐号都有一个account_type(单个字符)。 I need to do the following: 我需要执行以下操作:

  1. find all accounts with a type of A or B. 查找所有类型为A或B的帐户。
  2. store that account number in a new table called year_end_close along with a time stamp of when that transaction takes place 将该帐号存储在名为year_end_close的新表中,并将该时间戳记发生该交易的时间
  3. set all accounts in master with a type of A to C, and all accounts with a type of B to D 设置主帐户中所有类型为A到C的帐户,以及所有类型为B到D的帐户

What's the best way to handle this in SQL? 在SQL中处理此问题的最佳方法是什么? While loop? 虽然循环? Case statement? 案件陈述? Cursor? 光标? Any help is appreciated. 任何帮助表示赞赏。 The table has about 17,000 rows. 该表有大约17,000行。

You shouldn't need to use a cursor/loop to do something like this. 您不需要使用游标/循环来执行类似的操作。 When writing SQL, always try to look for a set-based solution first. 编写SQL时,请始终先尝试寻找基于集合的解决方案。 I would recommend a CASE statement, which was one of the options you mentioned. 我建议您使用CASE语句,这是您提到的选项之一。

Try this: 尝试这个:

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;

Are you searching for something like this? 您是否正在寻找类似的东西? (Replace the 'PRINT' statements for your actual SQL statements) (将“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM