一种方法是使用UNION ALL
并将CROSS APPLY
它们与您的行连接:
SELECT p.ID, p.Name ,p.Value, x.Col AS Manager
FROM dbo.Persons p
CROSS APPLY (SELECT Col FROM (SELECT 'Steve' UNION ALL SELECT 'Bill')AS T(Col))X
如果管理器是逗号分隔的列表,您需要 SQL-Server 2005 中的拆分功能,例如:
CREATE FUNCTION [dbo].[Split]
(
@ItemList NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))
AS
BEGIN
DECLARE @tempItemList NVARCHAR(MAX)
SET @tempItemList = @ItemList
DECLARE @i INT
DECLARE @Item NVARCHAR(4000)
SET @tempItemList = REPLACE (@tempItemList, ' ', '')
SET @i = CHARINDEX(@delimiter, @tempItemList)
WHILE (LEN(@tempItemList) > 0)
BEGIN
IF @i = 0
SET @Item = @tempItemList
ELSE
SET @Item = LEFT(@tempItemList, @i - 1)
INSERT INTO @IDTable(Item) VALUES(@Item)
IF @i = 0
SET @tempItemList = ''
ELSE
SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
SET @i = CHARINDEX(@delimiter, @tempItemList)
END
RETURN
END
现在这有效:
SELECT p.ID, p.Name ,p.Value, s.Item AS Manager
FROM dbo.Persons p
CROSS APPLY dbo.Split('Steve,Bill', ',')s
结果(SQL-Fiddle 已关闭):
ID Name Value Manager
1 Mike 404 Steve
2 John 404 Steve
1 Mike 404 Bill
2 John 404 Bill