<2009年7月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678


转载请保留链接

我的标签

随笔档案

宝宝孕历

  • 宝宝孕历
  • 宝宝孕历准爸爸准妈妈的好朋友-获得孕期每月每周的注意事项和温馨提示,记录宝宝诞生期间甜酸苦辣的甜蜜艰辛
  • 当当卓越比价程序
  • 用当当卓越比价程序,网上买书省钱省时。java与模式可以省10将近块钱
  • 怀孕书,育儿书,孕妇装
  • 宝宝孕历孕前准备书,怀孕书,育儿书,孕妇装,靠枕等新鲜出炉了
  • 孕期知识
  • 孕期的相关知识
  • 孕味广场
  • 孕期论坛,讨论怀孕,孕期注意事项,孕检等

最新随笔

最新评论

阅读排行榜

评论排行榜

Cross Apply使表可以和表值函数结果进行join,在下面的示例中建了两个表和一个表值函数,T_b的列a_ids中会存放a表的id,分割的字符串连接;我们通过cross apply使T_aT_b表通过splitIDs inner join 连接。请看示例:GO

if object_id('T_a','U') is not null
drop table T_a
GO

CREATE TABLE T_a(    id int unique not null,
    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')

INSERT INTO T_b VALUES(1,'B-1','1,2,4')
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的用法了吗?有问题欢迎讨论。
----------------------- 

相关随笔
· Sql Server2005对t-sql的增强之通用表表达式CTE
· Sql Server2005对t-sql的增强之top
· 用Clr实现的sql表值函数splitIDs
· Sql Server2005对t-sql的增强之排名函数

Tag标签: t-sql,sql,cross apply
posted on 2008-04-30 12:41 玉开 阅读(2366) 评论(4)  编辑 收藏 网摘 所属分类: 数据库sql server

FeedBack:
#1楼 2008-04-30 13:16 李战      
http://www.cnblogs.com/Emoticons/qface/055243188.gif" alt="" />很好,对俺有用。谢谢指点
  回复  引用  查看    
very good
  回复  引用    
#3楼 2008-09-23 10:17 zhenmu[未注册用户]
3x for your help.
  回复  引用    



发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 1177554




相关文章:

相关链接: