有很多方法可以實現所需的輸出。我的解決方案使用遊標和動態TSQL的組合。
下面是代碼,評論步步:
--1. create test tables
create table table1 ([Name] nvarchar(50),[Date] nvarchar(50))
create table table2 ([Date] nvarchar(50),Bob nvarchar(50),Jon nvarchar(50),Stu nvarchar(50),Amy nvarchar(50))
create table table3 ([Name] nvarchar(50),[Date] nvarchar(50),[Letter] nvarchar(50))
--2. populate test tables
insert into table1
select 'Bob','D1'
union all select 'Jon','D2'
union all select 'Stu','D3'
union all select 'Amy','D4'
insert into table2
select 'D1','A','B','C','D'
union all select 'D2','B','C','D','A'
union all select 'D3','C','D','A','B'
union all select 'D4','D','A','B','C'
--3. declare variables
DECLARE @query NVARCHAR(max); --this variable will hold the dynamic TSQL query
DECLARE @name NVARCHAR(50);
DECLARE @date NVARCHAR(50);
DECLARE @result NVARCHAR(50) --this variable will hold "letter" value returned by dynamic TSQL query
DECLARE @testCursor CURSOR;
--4. define the cursor that will scan all rows in table1
SET @testCursor = CURSOR FOR SELECT [Name], [Date] FROM table1;
OPEN @testCursor;
FETCH NEXT FROM @testCursor INTO @name, @date;
WHILE @@FETCH_STATUS = 0
BEGIN
--5. for each row in table 1 create a dynamic query that retrieves the correct "Letter" value from table2
set @query = 'select @res=' + @name + ' from table2 where [Date] =''' + @date +''''
--6. executes dynamic TSQL query saving result in @result variable
EXECUTE sp_executesql @query, N'@res nvarchar(50) OUTPUT', @[email protected] OUTPUT
--inserts data in table3 that holds final results
insert into table3 select @name, @date, @result
FETCH NEXT FROM @testCursor INTO @name, @date;
END
CLOSE @testCursor;
DEALLOCATE @testCursor;
select * from table1
select * from table2
select * from table3
下面是結果。前兩個表顯示輸入,第三個表包含實際的結果: