1

我有一个 proc 执行如下选择和更新语句。我需要将更新语句和将数据放入临时表的 select 语句合并到单个 sql select 语句中。

这可能吗?

             '                     
4

2 回答 2

0

我通过使用联合找到了一种出路。这有点奇怪,但由于我找不到其他任何东西,所以用这种方法解决

于 2014-01-06T06:23:32.930 回答
0

是的:

CREATE TABLE TableA
(
    valueA int
)

INSERT INTO 
    TableA
VALUES
    (1),
    (2),
    (3)

GO

CREATE PROCEDURE test_procedure (@in_value int)
AS
    BEGIN

        --insert into temp table
        SELECT
            @in_value [out_value]
        INTO 
            #TestTable

        -- update with join on temp table
        UPDATE
            T
        SET
            T.[out_value] = 2
        FROM
            #TestTable T
            INNER JOIN TableA A on A.valueA = T.out_value
        WHERE
            A.valueA = 1

        -- update with join on temp table again
        UPDATE
            T
        SET
            [out_value] = 3
        FROM
            #TestTable T
            INNER JOIN TableA A on A.valueA = T.out_value
        WHERE
            A.valueA = 2

        --select results including the original "in_value"
        SELECT 
            *, 
            @in_value [in_value]
        FROM
            TableA A
            LEFT JOIN #TestTable T on T.out_value = A.valueA
    END;
GO

--execute stored procedure
EXEC test_procedure 1
于 2013-11-01T21:43:10.297 回答