在Sql Query中需要帮助才能连接三个表

时间:2014-05-23 16:52:58

标签: sql sql-server sql-server-2008

我有三个表,如下面的格式所示。

create table Information(InfoID int, TOEmailIDKey varchar(100),
      CCEmailIDKey varchar(100))

create table userdata(UserKey int, name varchar(50), EmailIDs varchar(100))

create table emailusers(EmailUserKey int, username varchar(100), 
       UsersMailIDs varchar(100))


insert into Information select 1,'100,101,102','201,202,203'

insert into userdata

select 201,'test','Test@test.com' union
select 202,'test2','Test2@test.com' UNION
select 203,'test3','Test3@test.com' 

insert into emailusers
select 100,'sample','sample@test.com' union
select 101,'sample2','sample2@test.com' union
select 102,'sample3','sample3@test.com' 
select * from Information
select * from userdata
select * from emailusers

从以上三个表中我想要输出如下

TOMails(column1)                                       
sample@test.com,sample2@test.com,
sample3@test.com 

CCEmail (colum2)
Test.@test.com,Test2@test.com,Test3@test.com                                                     

1 个答案:

答案 0 :(得分:1)

创建一个这样的函数:

CREATE FUNCTION dbo.splitstring (@stringToSplit varchar(MAX))
RETURNS 
@returnList TABLE ([Name] [nvarchar] (500))
AS 
BEGIN

DECLARE @name nvarchar(255)
DECLARE @pos INT

WHILE CHARINDEX (',', @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX (',', @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

INSERT INTO @returnList
SELECT @name

SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
END 
INSERT INTO @returnList
SELECT @stringToSplit
RETURN
END
GO

然后你就可以:

DECLARE @string varchar(50)
DECLARE @tmp VARCHAR(250)
SET @string = (SELECT CCEmailIDKey FROM Information)
SET @tmp = ''

SELECT @tmp = @tmp + EmailIDs + ', ' 
FROM
(
    SELECT 
      u.EmailIDs 
    FROM 
      userdata u 
        JOIN dbo.splitstring(@string) s ON u.UserKey = s.name
) s

SELECT SUBSTRING(@tmp, 0, LEN(@tmp))
GO

DECLARE @string varchar(50)
DECLARE @tmp VARCHAR(250)
SET @string = (SELECT TOEmailIDKey FROM Information)
SET @tmp = ''

SELECT @tmp = @tmp + UsersMailIDs + ', ' 
FROM
(
    SELECT 
      u.UsersMailIDs 
    FROM 
      emailusers u 
        JOIN dbo.splitstring(@string) s ON u.EmailUserKey = s.name
) s

SELECT SUBSTRING(@tmp, 0, LEN(@tmp))
GO

无论您的数据发生了什么变化,结果都会如您所愿。

SQL Fiddle

结合这两个答案:

Convert multiple rows into one with comma as separator

Tsql split string