Sql Server2005对t-sql的增强之Cross Apply
if?object_id('T_a','U')?is?not?null
drop?table?T_a
GO
????name?varchar(50),
)
GO
if?object_id('T_b',N'U')?is?not?null
drop?table?T_b
GO
create?table?T_b
(
????id?int?unique?not?null,
????name?varchar(10),
????a_ids?varchar(100)?null?--要在這一列中存放t_a表的ID序列,這樣做連第一范式都沒有滿足,但是有時候考慮性能或設計我們可能會像這么用
)
GO
--初始化數據
INSERT?INTO?T_a?VALUES(1,'A-1')
INSERT?INTO?T_a?VALUES(2,'A-2')
INSERT?INTO?T_a?VALUES(3,'A-3')
INSERT?INTO?T_a?VALUES(4,'A-4')
INSERT?INTO?T_a?VALUES(5,'A-5')
GO
--創建一個表值函數,用來拆分用逗號分割的數字串,返回只有一列數字的表
if?object_id('splitIDs','TF')?is?not?null
drop?function?splitIDs;
GO
create?function?splitIDs(
????@Ids?nvarchar(1000)
)
returns?@t_id?TABLE?(id?bigint)
as
begin
????declare?@i?int,@j?int,@l?int,@v?bigint;
????set?@i?=?0;
????set?@j?=?0;
????set?@l?=?len(@Ids);
????while(@j?<?@l)
????begin
???????set?@j?=?charindex(',',@Ids,@i+1);
???????if(@j?=?0)?set?@j?=?@l+1;
???????set?@v?=?cast(SUBSTRING(@Ids,@i+1,@j-@i-1)?as?bigint);
???????INSERT?INTO?@t_id?VALUES(@v)
???????set?@i?=?@j;
????end
????return;
end
GO
--測試splitIDs的執行效果
select?*?from?splitIDs('1,2,4,3')
select?*?from?splitIDs('100')
select?*?from?splitIDs(NULL)
GO
--使用cross apply獲得t_b表中指定行對應的所有t_a表中的記錄
select?
????aid?=?t_a.id
????,aname?=?t_a.name
????,bid?=?t_b.id
from?t_b
cross?apply?splitIDs(a_ids)?tbl_Ids
INNER?JOIN?t_a?ON?tbl_Ids?.id?=?t_a.id
where?t_b.id?=?1
你明白cross apply的用法了嗎?有問題歡迎討論。
轉載于:https://www.cnblogs.com/yanbinboy/archive/2008/04/30/1177811.html
總結
以上是生活随笔為你收集整理的Sql Server2005对t-sql的增强之Cross Apply的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 慕课软件质量保证与测试(总目录)
- 下一篇: html语言中行距如何设定,html怎么