Cross apply不是很懂
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') INSERT INTO T_b VALUES(2,'B-1','2,3,5') INSERT INTO T_b VALUES(3,'B-1','6,7,8') 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 select * from T_a select * from T_b --使用cross apply获得t_b表中指定行对应的所有t_a表中的记录 select * --, -- aid = t_a.id -- ,aname = t_a.name -- ,bid = t_b.id from t_b outer apply splitIDs(a_ids) tbl_Ids INNER JOIN t_a ON tbl_Ids .id = t_a.id where t_b.id = 1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决