简体   繁体   English

在SQL Server中创建动态联合查询

[英]To creating a dynamic union query in sql server

I am trying to loop through my counter to create a dynamic sql query which should finally look like 我试图遍历我的计数器以创建一个动态sql查询,该查询最终看起来应该像

I am trying to use this approach to get the final query but doesnt seems to work 我正在尝试使用这种方法来获取最终查询,但似乎不起作用

declare @CurrentRow int 
set @CurrentRow =0;
declare @RowsToProcess int
declare @FinalHistoricalQuery varchar(5000)
WHILE @CurrentRow<3
 BEGIN       
   SET @FinalHistoricalQuery =' select 11'+convert(varchar(20),@CurrentRow) + ' union '
   SET @CurrentRow=@CurrentRow+1
 END

SET @FinalHistoricalQuery = left(@FinalHistoricalQuery,len(@FinalHistoricalQuery)-6)
exec (@FinalHistoricalQuery)

the final ouput that i am looking for is 110 111 112 but it comes as 112 Any suggestion would be helpfull 我正在寻找的最终输出是110 111 112,但它的输出结果是112任何建议都会有所帮助

You missed to use the counter in dynamic query . 您错过了在dynamic query使用计数器的功能。 Try something like this. 尝试这样的事情。

WHILE @CurrentRow<@RowsToProcess
 BEGIN       
   SET @FinalHistoricalQuery +=' select id from table'+convert(varchar(20),@CurrentRow) + ' union '
   SET @CurrentRow=@CurrentRow+1
 END

SET @FinalHistoricalQuery = left(@FinalHistoricalQuery,len(@FinalHistoricalQuery)-6)
exec (@FinalHistoricalQuery)

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

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