函数在执行时返回错误的值

时间:2013-07-24 12:24:22

标签: sql-server

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

ALTER procedure [dbo].[fetchkey]
@carid nvarchar(50) =null
as
begin
 select t.TBarcode, t.Status, [dbo].[keyloc](t.Status) as 'Key location'
from Transaction_tbl t 
 where t.TBarcode=@carid
end

我有一个与此存储过程关联的函数:

ALTER function [dbo].[keyloc](@status numeric(18,2)) RETURNS varchar(50)
as  begin  declare 
@car nvarchar(100), @keylocation  Varchar(50)
 if @status=0
begin
select @car =  t1.TBarcode from Transaction_tbl t1 
  select @keylocation='With Employee'+'('+@car+')'
return @keylocation
end

我正在通过carid作为Tbarcode,但执行输出时出错了

my output:

    TBarcode             Status      Key location
    -------------------- ----------- ----------------------
    53012364813          0           With Employee(717164016319).

我希望在With Employee中获得相同的Tbarcode

Expected output

    TBarcode             Status      Key location
    -------------------- ----------- ----------------------
    53012364813          0           With Employee(53012364813).

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

你要回来了

select @car =  t1.TBarcode from Transaction_tbl t1  

这来自你的功能。由于它没有正确的where条款@car is assigned by the first value of TBarcode

因此,该函数从TBarcode返回Transaction_tbl的第一个值作为输出

试试这个

ALTER function [dbo].[keyloc](@status numeric(18,2),@cardID VARCHAR(50)/*Newly added*/)
 RETURNS varchar(50)
ASbegin  declare 
  @car nvarchar(100), @keylocation  Varchar(50)
   if @status=0
  begin
    select @car =  t1.TBarcode 
    from Transaction_tbl t1 
    WHERE t1.TBarcode =@cardID 
    select @keylocation='With Employee'+'('+@car+')'

return @keylocation
end

程序

ALTER procedure [dbo].[fetchkey]
@carid nvarchar(50) =null
as
begin
 select t.TBarcode, t.Status,
 [dbo].[keyloc](t.Status,@carid/*newly added*/) as 'Key location'
from Transaction_tbl t 
 where t.TBarcode=@carid
end