我需要多次使用带有UNION ALL的SELECT语句(未知没有'次)

时间:2013-12-09 18:02:45

标签: c# union

我需要多次使用带有UNION ALL的SELECT语句(未知数次)。 我用c#做到了!我可以在存储过程中执行此操作吗?

C#

// this code selects a number of users thoughts. for every user it is getting only 6 thoughts
// according to each user page number (friendsToughtPageNum).   
for (int i = startUser-1; i < endUser; i++){
     subSql += "SELECT * FROM (SELECT TOP " + 6 * friendsToughtPageNum[i] + " * FROM (SELECT TOP  thought, firstName, lastName  FROM tbl_thoughts INNER JOIN tbl_users ON thoughtUserID = userID WHERE userID=" + IDs[i] + " ORDER BY thoughtID ASC) AS T" + i + " ORDER BY thoughtID DESC) AS TA" + i + " UNION ALL ";
                }
     subSql = subSql.Remove(subSql.Length - 11, 11);
     sql = subSql;

1 个答案:

答案 0 :(得分:0)

是的,您可以使用CURSOR并以此方式循环在存储过程中执行此操作。然后,您可以将结果保存到临时表并从中读取,或者您可以继续使用UNION ALL