简体   繁体   English

在另一个SQL查询中使用一个查询的结果

[英]Use result of one query in another sql query

I have below table structure : 我有下面的表结构:

Table1 表格1

╔═════╦══════╦═════════════╦═════════════╗
║Col1 ║ Col2 ║ TableName   ║ ColumnName  ║
╠═════╬══════╬═════════════╬═════════════╣
║  1  ║ abc  ║ Table2      ║ column2     ║
║  2  ║ xyz  ║             ║             ║
║  3  ║ pqr  ║ Table1      ║ column1     ║
║  4  ║ jbn  ║             ║             ║
╚═════╩════════════════════╩═════════════╝

Table2 :   

 ╔════════╦═════════╗
 ║Column1 ║ Column2 ║
 ╠════════╬═════════╣
 ║  1     ║ A       ║
 ║  2     ║ B       ║
 ║  3     ║ C       ║
 ║  4     ║ D       ║
 ╚════════╩═════════╝

Table3

╔════════╦═════════╗
║Column1 ║ Column2 ║
╠════════╬═════════╣
║  1     ║ X       ║
║  2     ║ Y       ║
║  3     ║ Z       ║
║  4     ║ A       ║
╚════════╩═════════╝

I want to write stored procedure which will select data from Table1 and data from another table depending upon value of column tableName and columnName in Table1. 我想写一个存储过程,它将根据Table1中的tableName和columnName列的值从Table1中选择数据,并从另一个表中选择数据。

I want data in following format: 我想要以下格式的数据:

╔═════╦═════╦════════╗
║Col1 ║ Col2║ List   ║
╠═════╬═════╬════════╣
║  1  ║ abc ║A,B,C,D ║
║  2  ║ xyz ║        ║
║  3  ║ pqr ║1,2,3,4 ║
║  4  ║ jbn ║        ║
╚═════╩═════╩════════╝

Try temporary table . 尝试临时表。 look at here : http://www.sqlteam.com/article/temporary-tables 在这里看: http : //www.sqlteam.com/article/temporary-tables

You will need a dynamic sql to get such a select. 您将需要一个动态sql来获得这样的选择。 Check out the link http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/ 查看链接http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

EDIT: 编辑:

The following code should do the trick. 以下代码可以解决问题。

I have assumed that the column Col1 in Table1 is of type int. 我假设Table1中的列Col1是int类型。

I have used Temp table to generate the required table. 我已使用Temp表生成所需的表。 You can replace it will your table as per your convenience. 您可以根据需要方便地将其替换成桌子。 Also I have used #table1 which you can replace with your Table1 . 我还使用了#table1 ,可以将其替换为Table1

Also this might not be very good in terms of performance but this is the best I could come up with right now. 同样,这在性能方面可能不是很好,但这是我现在能想到的最好的方法。

declare @count int, @Query VARCHAR(5000), @counter int, @tableName VARCHAR(50), @ColumnName VARCHAR(50), @Col1 INT, @Col2 VARCHAR(50)
select @count = count(0) from #table1
SET @counter = 1

CREATE TABLE #table4
(
    Col1 INT,
    Col2 VARCHAR(50),
    List VARCHAR(50)
)

WHILE @counter <= @count
BEGIN
    SELECT @tableName = TableName, @ColumnName = columnName, @Col1 = Col1, @Col2 = Col2 FROM #Table1 WHERE Col1 = @counter

    SELECT @Query = 'INSERT INTO #table4 (Col1 , Col2) VALUES (' + CONVERT(varchar(50),@Col1) + ', ''' + @Col2 + ''')'
    EXEC (@Query)
    SELECT @Query = ''

    IF ISNULL(@tableName, '') != '' AND ISNULL(@ColumnName, '') != ''
    BEGIN
        SELECT @Query = 'UPDATE #table4 SET LIST = STUFF((SELECT '','' + CONVERT(VARCHAR(50), ' + @ColumnName + ') FROM ' + @tableName + ' FOR XML PATH('''')),1,1,'''') WHERE Col1 = ' + CONVERT(varchar(50),@Col1)

        EXEC (@Query)
    END
    SET @counter = @counter + 1
END

SELECT * FROM #table4

Hope this helps 希望这可以帮助

Answer edited for incorporating n no of rows 已编辑答案以合并n行

CODE

 drop table #temp1
declare @tabletemp as varchar (10)
declare @columntemp as varchar (10)
Declare @sqlTemp NVARCHAR(400)
declare @counter1 as int
declare @counter2 as int
select @counter2 = 1

select name,cname into #temp1 from test1
select @counter1 = COUNT(*) from #temp1


while (@counter2<= @counter1)
begin
SET @tabletemp = (SELECT MIN(name) FROM #temp1)
select @columntemp = (select min(cname) from #temp1 where #temp1.name = @tabletemp)

set @sqlTemp='select '+@columntemp +'  from '+@tabletemp
exec(@sqlTemp)

delete from #temp1 where name = @tabletemp and cname = @columntemp

select @counter1 = COUNT(*) from #temp1
end

RESULT 结果

select * from test1 
name    cname
table1  column1
test2   colname
table1  test
test2   name

select column1 from table1
column1
qwer
asdff
zxcvb
qwer
asdff
zxcvb

select colname from test2
colname
testing
wer
ewrth
sfsf
testing
wer
ewrth
sfsf

select test from table1
--got error message inavlid column nae 'test' as this column does not exist

select name from test2 
name
table1
table1
table3
table2
table1
table1
table3
table2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM