日期:2014-05-17 浏览次数:20469 次
--> 测试数据:[DB_Emp] IF OBJECT_ID('[DB_Emp]') IS NOT NULL DROP TABLE [DB_Emp] GO CREATE TABLE [DB_Emp]([Emp_Id] INT,[name] VARCHAR(4)) INSERT [DB_Emp] SELECT 1,'张三' UNION ALL SELECT 2,'李四' UNION ALL SELECT 3,'杜明' UNION ALL SELECT 4,'李果' UNION ALL SELECT 5,'赵刚' --> 测试数据:[DB_Emp_Like] IF OBJECT_ID('[DB_Emp_Like]') IS NOT NULL DROP TABLE [DB_Emp_Like] GO CREATE TABLE [DB_Emp_Like]([Emp_Id] INT,[Like_No] INT) INSERT [DB_Emp_Like] SELECT 1,101 UNION ALL SELECT 1,102 UNION ALL SELECT 1,105 UNION ALL SELECT 3,101 UNION ALL SELECT 3,105 UNION ALL SELECT 4,101 UNION ALL SELECT 4,102 UNION ALL SELECT 5,101 UNION ALL SELECT 5,102 UNION ALL SELECT 5,103 --> 测试数据:[DB_Like] IF OBJECT_ID('[DB_Like]') IS NOT NULL DROP TABLE [DB_Like] GO CREATE TABLE [DB_Like]([Like_No] INT,[Name] VARCHAR(8)) INSERT [DB_Like] SELECT 101,'打篮球' UNION ALL SELECT 102,'打乒乓球' UNION ALL SELECT 103,'唱歌' UNION ALL SELECT 104,'登山' UNION ALL SELECT 105,'游泳' --------------开始查询-------------------------- IF OBJECT_ID('F_Str') IS NOT NULL DROP FUNCTION F_Str go CREATE FUNCTION F_Str ( @Emp_Id INT ) RETURNS VARCHAR(100) AS BEGIN DECLARE @S VARCHAR(100) SELECT @S = ISNULL(@S + ',', '') + c.[Name] FROM [DB_Emp_Like] b , [DB_Like] c WHERE b.[Like_No] = c.[Like_No] AND b.[Emp_Id] = @Emp_Id RETURN @S END go SELECT DISTINCT a.[Emp_Id],a.[name],name=dbo.F_Str(a.[Emp_Id]) FROM [DB_Emp] a,[DB_Emp_Like] b WHERE a.[Emp_Id]=b.[Emp_Id] /* Emp_Id name name ----------- ---- ---------------------------------------------------------------- 1 张三 打篮球,打乒乓球,游泳 3 杜明 打篮球,游泳 4 李果 打篮球,打乒乓球 5 赵刚 打篮球,打乒乓球,唱歌 (4 行受影响) */
------解决方案--------------------
将#4楼改成以下便可
IF OBJECT_ID('F_Str') IS NOT NULL DROP FUNCTION F_Str go CREATE FUNCTION F_Str ( @Like_No INT ) RETURNS VARCHAR(100) AS BEGIN DECLARE @S VARCHAR(100) SELECT @S = ISNULL(@S + ',', '') + a.[name] FROM [DB_Emp] a, [DB_Emp_Like] b WHERE a.[Emp_Id] = b.[Emp_Id] AND b.[Like_No] = @Like_No RETURN @S END go SELECT DISTINCT b.[Name],name=dbo.F_Str(a.[Like_No]) FROM [DB_Emp_Like] a,[DB_Like] b WHERE a.[Like_No]=b.[Like_No]