MSSQL存储过程/临时表/多行更新/使用TOP 1

时间:2019-02-04 18:28:55

标签: sql-server-2008 stored-procedures sql-update

我有一个存储过程,其中存储了一个临时表:

my_list= [['1', '2', '4'], ['1', '48', '2'], ['53', '33', '25', '2', '26', '47']]
new_list = [[i[j],i[j+1]] for i in my_list for j in range(i.index('2'))]

我从SQL Manager收到一条错误消息,即#tempLocal.AB不能绑定多部分标识符“#tempLocal.AB”。我在这里做什么错了?

注意:这是当前的更新部分,正在运行,但是我在想,也许我不必要选择3次,而我可以一次。

ALTER PROCEDURE [dbo].[spBestellungStand]
(
    @Start datetime,
    @Stop datetime
)
as
BEGIN
    create TABLE #tempLocal(
        AB int,
        AH_IDENT int,
        AH_NAME1 nvarchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
        STATUS int,
        DATUM_ERF datetime,
        FI_BETR_NETTO float,
        BEST_TEXT2 nvarchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
        FI_ZAHLBED nvarchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
        DB_YEAR int,
        WARENEINGANG datetime,
        AB_LIEFERANT nvarchar(50),
        NR_RECHNUNG nvarchar(50),
        DATUM_RECHNUNG datetime,
        AB_LIEFERANT2 nvarchar(50),
        NR_RECHNUNG2 nvarchar(50),
        DATUM_RECHNUNG2 datetime,       
        AB_LIEFERANT3 nvarchar(50),
        NR_RECHNUNG3 nvarchar(50),
        DATUM_RECHNUNG3 datetime,   
        CUST_AH_IDENT int,
        CUST_AH_NAME1 nvarchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
        CUST_FI_BETR_NETTO float,
        CUST_DB_YEAR int,
        CUST_LIEFERSCHEIN datetime,
        CUST_RECHNUNG datetime      
    )


    insert into #tempLocal
        select AB,AH_IDENT,AH_NAME1,STATUS,DATUM_ERF,FI_BETR_NETTO,SUBSTRING(BEST_TEXT2,1,LEN(BEST_TEXT2)-CHARINDEX('/',BEST_TEXT2,1)+1) as Best_Text2,
        FI_ZAHLBED,DB_YEAR,null,'','',null,'','',null,'','',null,null,null,null,null,null,null
        from BW_BEST_KOPF
        --where DATUM_ERF >= @start and DATUM_ERF <= @stop

    -- WARENEINGANG 
    update #tempLocal 
    set WARENEINGANG=convert(date, (select top 1 DATUM from BW_BEST_HIST where AB=#tempLocal.AB and DB_YEAR=#tempLocal.DB_YEAR
    and STATUS_ID in (61,62) order by DATUM desc))

    -- AB LIEFERANT, NR RECHNUNG , DATUM RECHNUNG 
    update #tempLocal
      set AB_LIEFERANT = CD.AB_LIEFERANT, NR_RECHNUNG = CD.NR_Rechnung, DATUM_RECHNUNG = CD.Rech_Datum
    from
    (
    select top 1 AB_LIEFERANT, NR_Rechnung, Rech_Datum from BW_BEST_MAN
    where BW_BEST_MAN.BEST_ID = #tempLocal.AB
    order by BW_BEST_MAN.DB_YEAR desc
    ) as CD

任何帮助表示赞赏。谢谢。

更新1:

所以我设法做到了:

update #tempLocal
set AB_LIEFERANT=(select top 1 AB_LIEFERANT from BW_BEST_MAN where BEST_ID=#tempLocal.AB order by DB_YEAR desc),
    NR_RECHNUNG=(select top 1 NR_Rechnung from BW_BEST_MAN where BEST_ID=#tempLocal.AB order by DB_YEAR desc),
    DATUM_RECHNUNG=(select top 1 Rech_Datum from BW_BEST_MAN where BEST_ID=#tempLocal.AB order by DB_YEAR desc)

这可行,但是我不确定100%是否可以节省任何服务器资源。 那就比使用TOP1的子查询高3倍吗?

更新2:

好吧,使用单个查询确实可以提高速度, 3x子查询是每次00:00:41,然后一个查询是每次00:00:33。不多 。我想我每天可能只会刷新一次此数据。

0 个答案:

没有答案