寻找光标的替代品

时间:2015-07-02 20:27:43

标签: sql sql-server tsql

我试图找出一种更好,更有效的方法来编写下面的脚本。谁能想到一种不使用游标就能实现同一目标的方法?

"用户" table1中可能会出现多次,但在table2中只能出现一次。

TABLE1

|Name   |Access   |
-------------------
User1   |N        |
User1   |N        |
User1   |Y        |

TABLE2

|Name   |Access   |
-------------------
User1   |         |
User2   |         |
User3   |         |

代码:

DECLARE @Name VarChar(50), @Access VarChar(1)

DECLARE TestCursor CURSOR FOR 
    SELECT Name, Access FROM Table1 ORDER BY Obj ASC

OPEN TestCursor
FETCH NEXT FROM TestCursor INTO @Name, @Access

WHILE @@FETCH_STATUS = 0 
BEGIN 
    UPDATE table2 
    SET Table2.Access = CASE 
                            WHEN Table1.Access = 'Y' THEN Table1.Access
                        ELSE Table2.Access END
    FROM table1 
    JOIN table2 ON table1.name = table2.name

    FETCH NEXT FROM TestCursor INTO @Name, @Access
END 

CLOSE TestCursor 
DEALLOCATE TestCursor

2 个答案:

答案 0 :(得分:1)

UPDATE  t2
SET     access = t1.access
FROM    (
        SELECT  name, MAX(CASE access WHEN 'Y' THEN 'Y' END) access
        FROM    table1
        GROUP BY
                name
        ) t1
JOIN    table2 t2
ON      t2.name = t1.name
        AND t1.access = 'Y'
WHERE   EXISTS
        (
        SELECT  t1.access
        EXCEPT
        SELECT  t2.access
        )

答案 1 :(得分:1)

我理解的是,只有当table1的最新(由max obj列定义)访问为“Y”时,才想更新Table2的访问列。

试试这个:

UPDATE @Table2
SET Access = CA.Access
FROM @Table2 AS T2
CROSS APPLY (
                SELECT TOP 1 Access 
                FROM @Table1 AS T1
                WHERE       T1.Name = T2.Name
                        AND T1.Access = 'Y'
                ORDER BY Obj DESC
            ) CA