0
我想寫查詢,並與一個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做到這一點。 – jean
@jean同意,如果可能,我會避免函數調用 – Jayvee