使用一个SQL脚本提取两组数据

时间:2012-11-30 16:03:17

标签: sql sql-server sql-server-2008

我希望能够在一个脚本中提取两组数据,共有15条记录。

在我的场景中,我从某个城镇中提取成员,例如可以返回3个记录,然后我想从该特定状态中提取剩余的12个。

这是一个编码样本:

SELECT MemberID, a.UserName, a.MemberDisplayName, a.NYKABizName, a.PackageType
FROM Member a
WHERE a.Claimed = 'Y'
AND a.PrCity = 'Bridgewater'
AND a.PrStateID = 36
AND a.PackageType = 'E'
ORDER BY a.MemberDisplayName

SELECT MemberID, a.UserName, a.MemberDisplayName, a.NYKABizName, a.PackageType
FROM Member a
WHERE a.Claimed = 'Y'
AND a.PrStateID = 36
AND a.PackageType = 'E'
ORDER BY a.MemberDisplayName

我不希望将这两者组合成一个,我想要一个存储结果的临时虚拟表,然后在完成后返回虚拟表。

任何想法如何实现这一目标?

非常感谢, neojakey

2 个答案:

答案 0 :(得分:2)

您的virtual table看起来像这样

CREATE VIEW view_name AS
    SELECT * FROM
    (
    SELECT MemberID, a.UserName, a.MemberDisplayName, a.NYKABizName, a.PackageType
    FROM Member a
    WHERE a.Claimed = 'Y'
    AND a.PrCity = 'Bridgewater'
    AND a.PrStateID = 36
    AND a.PackageType = 'E'
    ORDER BY a.MemberDisplayName
    ) x 
    UNION 
    (
    SELECT MemberID, a.UserName, a.MemberDisplayName, a.NYKABizName, a.PackageType
    FROM Member a
    WHERE a.Claimed = 'Y'
    AND a.PrStateID = 36
    AND a.PackageType = 'E'
    ORDER BY a.MemberDisplayName
    ) y

答案 1 :(得分:0)

您可以在数据适配器中传递多个select语句,以“;”分隔。

SqlDataAdapter dataAdapter = new SqlDataAdapter(“select * from table1;select * from table2”, connection);

DataSet ds = new DataSet();

dataAdapter.Fill(ds);

然后您可以使用ds.Tables [index]。

引用结果集

C# DataAdapter and DataSet with multiple table