日期:2014-05-17 浏览次数:20411 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-03-28 21:44:51
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([ID] int,[姓名] varchar(4),[手机] int)
insert [a]
select 1,'小张',1234 union all
select 2,'小王',5678
--------------开始查询--------------------------
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go
create table [b]([ID] int,[喜爱] varchar(4))
insert [b]
select 1,'唱歌' union all
select 1,'跳舞' union all
select 1,'喝酒' union all
select 2,'吃肉' union all
select 2,'弹琴' union all
select 1,'画画'
--------------开始查询--------------------------
--创建函数
create function [dbo].[F_Str](@id int)
returns nvarchar(1000)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+[喜爱] from B where id=@id
return @S
end
go
--查询
SELECT a.id,a.[姓名],a.[手机],b.[喜爱]
FROM a INNER JOIN (SELECT DISTINCT id,[喜爱]=dbo.f_str(id) FROM b)b ON a.id=b.id
----------------结果----------------------------
/*
id 姓名 手机 喜爱
----------- ---- ----------- ----------------------------------------------------------------------------------------------------------------