【问题标题】:Return list values with function使用函数返回列表值
【发布时间】:2014-03-07 16:53:45
【问题描述】:

我正在尝试编写查询,并且使用一张 card_nr 可以正常工作。示例:

Declare @card_nr as nvarchar(50)

set @card_nr = '704487442952000472'

select 
    a.times, b.times 
from 
    (select 
         stat_id, times 
     from info 
     where card_nr = @card_nr) as a 
left outer join 
    (select 
         stat_id, times 
     from info 
     where card_nr = @card_nr) as b on a.stat_id = b.stat_id+1

我得到了正确的结果:

2014-02-04 11:20:00.000 NULL
2014-02-06 09:44:00.000 2014-02-04 11:20:00.000
2014-02-12 09:59:00.000 2014-02-06 09:44:00.000
2014-02-13 10:31:00.000 2014-02-12 09:59:00.000
2014-02-21 09:49:00.000 2014-02-13 10:31:00.000

我想为表格列表中的每个card_nr 执行此操作。所以,首先我写了函数:

alter FUNCTION tabletest
   ( @card_nr as nvarchar(50))
RETURNS smalldatetime 
AS BEGIN
    Declare @sqldata as smalldatetime

    select 
        @sqldata = b.times 
    from 
        (select 
             stat_id, times 
         from info where card_nr = @card_nr) as a 
    left outer join 
        (select 
             stat_id, times 
         from info where card_nr = @card_nr ) as b on a.stat_id = b.stat_id + 1

   RETURN @datas 
END

在我尝试过的函数之后选择我的查询:

select name, times, dbo.tabletest(card_nr)
from dbo.info

我得到了错误的结果:

User1   2014-02-04 11:20:00.000 2014-02-21 09:49:00
User1   2014-02-06 09:44:00.000 2014-02-21 09:49:00
User1   2014-02-12 09:59:00.000 2014-02-21 09:49:00
User1   2014-02-13 10:31:00.000 2014-02-21 09:49:00
User1   2014-02-21 09:49:00.000 2014-02-21 09:49:00
User2   2014-02-14 13:41:00.000 2014-02-28 12:20:00
User2   2014-02-24 11:46:00.000 2014-02-28 12:20:00
User2   2014-02-28 12:20:00.000 2014-02-28 12:20:00

我想得到这个:

User1   2014-02-04 11:20:00.000 NULL
User1   2014-02-06 09:44:00.000 2014-02-04 11:20:00.000
User1   2014-02-13 10:31:00.000 2014-02-12 09:59:00.000
User1   2014-02-13 10:31:00.000 2014-02-12 09:59:00.000
User1   2014-02-21 09:49:00.000 2014-02-13 10:31:00.000
User2   2014-02-14 13:41:00.000 NULL
User2   2014-02-24 11:46:00.000 2014-02-14 13:41:00.000
User2   2014-02-28 12:20:00.000 2014-02-24 11:46:00.000

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    应该可以仅使用表格信息获得所需的结果:

     select name, times, 
     (select max(times) from info i2 where i2.times<i1.times and i1.name=i2.name and i2.card_nr=@card_nr ) 
     from info i1
     where  card_nr=@card_nr 
    

    【讨论】:

    • 我会尝试的,但如果我想使用该功能。正确的函数和查询是什么?
    • 我不想使用它们(至少是标量)有时会很慢的函数。根据经验,如果您可以使用“普通” sql 做到这一点,那么就这样做。
    • @jean 同意,如果可能的话,我会避免函数调用
    • 为什么?我想以另一种方式使用函数。你能帮我吗?是的,您的查询工作正常。
    • 您可以将此部分包装在函数中:select max(times) from info i2 where i2.times
    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2022-01-11
    • 2021-03-10
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多