选择和更新使用临时表存储过程中的select语句结果

时间:2017-03-27 01:53:25

标签: sql sql-server sql-server-2008

ALTER PROCEDURE sp_updateInward
    (@bl_num VARCHAR(30),
     @cg_type VARCHAR(10))
AS
    CREATE TABLE #temp_select
    (
        qty int,
        wght decimal(8,2),
        vol decimal(8,2) 
    )

    INSERT INTO #temp_select
        SELECT 
            CASE 
               WHEN @cg_type = 'BB' 
                  THEN SUM(ISNULL(CAST(t1.qty AS FLOAT), 0)) 
               ELSE 1 
            END AS qty,
            SUM(ISNULL(CAST(t1.wght AS FLOAT), 0)) AS wght,
            SUM(ISNULL(CAST (t1.vol AS FLOAT), 0)) AS vol
        FROM 
            godown_storage t1
        INNER JOIN 
            ccosbl t2 ON t2.id = t1.blso_id
        WHERE
            t2.bl_num = @bl_num

    UPDATE ccosblitem
    SET qty = #temp_select.quantity, 
        wght = #temp_select.weight, 
        vol = #temp_select.volume
    FROM ccosblitem t3
    INNER JOIN ccosbl t4 ON t4.id = t3.master_id 
    WHERE t4.bl_num = @bl_num

    SELECT * FROM ccosblitem

我需要从select语句更新ccosblitem。我在存储过程中执行它并创建临时表。我尝试使用declare变量,但它提示错误说' AS'是不正确的。

2 个答案:

答案 0 :(得分:0)

替换

发件人:

  ALTER PROCEDURE sp_updateInward
(
    @bl_num VARCHAR(30),
    @cg_type VARCHAR(10)
)
AS

ALTER PROCEDURE sp_updateInward @bl_num VARCHAR(30),@cg_type VARCHAR(10)
AS

begin
//your action here
end

答案 1 :(得分:0)

您的更新声明需要更改。您在SET子句中使用临时表列而不使用FROM子句中的临时表。另外,对于连接目的,您需要在临时表中具有ID列,并且需要在insert语句中填充相同的列。以下是对代码的更改。

CREATE TABLE #temp_select
    (
        id int,
        qty int,
        wght decimal(8,2),
        vol decimal(8,2) 
    )

SELECT T1.ID, case....

UPDATE ccosblitem
    SET qty = #temp_select.quantity, 
        wght = #temp_select.weight, 
        vol = #temp_select.volume
    FROM ccosblitem t3
    INNER JOIN #temp_select t4 ON t4.id = t3.master_id