同时在存储过程中添加case语句获取错误

时间:2014-05-03 08:16:29

标签: sql sql-server stored-procedures

我有一个像这样的存储过程:

SELECT

     k.HBarcode, m.make,t.Compl,
    t.plateno,t.self,t.dtime, v.vtype, l.locname,[dbo].[EDTCAL](t.TBarcode)as EDT,  t.locid,t.vtid,t.lsttic,
     c.Colname, te.UniqueName

  FROM transaction_tbl t

  left JOIN KHanger_tbl k ON t.transactID = k.transactID
  left JOIN make_tbl m ON t.mkid = m.mkid 

  left JOIN vtype_tbl v ON v.vtid = t.vtid 
  left  JOIN Location_tbl l ON t.locid = l.locid 

  left JOIN Color_tbl C ON t.colid = c.colid 
  left JOIN Terminals_tbl te ON k.tid = te.tid

 WHERE t.tbarcode = '0213'

我的功能如下:

ALTER function [dbo].[EDTCAL](@cardID VARCHAR(50)) RETURNS int
as 
begin
declare
@locid int,
@EDT int,
@minEDT int,
@buffEDT int,
@value int

select @locid= t.Locid from Transaction_tbl t where t.TBarcode=@cardID
select @EDT= l.EDT from Location_tbl l where l.Locid=@locid
select @minEDT=l.MinEDT  from Location_tbl l where l.Locid=@locid
select @buffEDT=l.BuffrEDT  from Location_tbl l where l.Locid=@locid 
if (@EDT is null) or (@EDT=0)
begin
select @value=@minEDT+@buffEDT
end 
else
begin
select @value=@EDT+@buffEDT
end
return @value
end

所以我的存储过程执行时间很慢..所以我从我的程序中删除了我的函数,我编写了这样的代码:

SELECT

     k.HBarcode, m.make,t.Compl,
    t.plateno,t.self,t.dtime, v.vtype, l.locname,case when l.edt is null or l.edt =0 then l.minEdt +l.bufferEdt else l.edt + l.bufferEdt end as EDT,  t.locid,t.vtid,t.lsttic,
     c.Colname, te.UniqueName

  FROM transaction_tbl t

  left JOIN KHanger_tbl k ON t.transactID = k.transactID
  left JOIN make_tbl m ON t.mkid = m.mkid 

  left JOIN vtype_tbl v ON v.vtid = t.vtid 
  left  JOIN Location_tbl l ON t.locid = l.locid 

  left JOIN Color_tbl C ON t.colid = c.colid 
  left JOIN Terminals_tbl te ON k.tid = te.tid

 WHERE t.tbarcode = '0213'

*但是收到错误: Msg 207,Level 16,State 1,Line 4 列名称无效' bufferEdt'。 Msg 207,Level 16,State 1,Line 4 列名称无效' bufferEdt'

我只添加了此代码

当l.edt为null或l.edt = 0然后l.minEdt + l.bufferEdt else l.edt + l.bufferEdt以EDT结尾

1 个答案:

答案 0 :(得分:0)

tbarcode ='0213'在执行计划中出现在哪里?应该在某个地方。使用它可能没有任何优势。如果在一般情况下你想要改善查询的执行时间,你可以完全摆脱udf并从基于连接的case语句中获取@minEDT + @ buffEDT和@valval = @EDT + @ buffEDT。

很抱歉在手机上这样做了。关键是你不需要一个单独的功能。用以下内容替换对udf的调用:     当l.edt为null或l.edt = 0然后l.minEdt + l.bufferEdt else l.edt + l.bufferEdt以EDT结尾

关键是你的udf会为返回的每一行执行单独的选择,从而增加执行时间。您不需要它,因为这些字段已经作为select语句的一部分返回。