如何将SQL查询结果放入多个表中

时间:2018-04-20 10:14:54

标签: sql sql-server

我的查询基本上非常简单:

SELECT id, 
       other_data 
FROM Data_Table 
WHERE id IN ( SELECT id 
              FROM Other_Table 
              WHERE other_id = @Selected_id
            )

我从C#向SQL Server运行此查询。 我希望将查询结果放入几个数据表中,而不是结果数据集中的一个数据表。

所以,基本上查询的结果应该是这样的:

id,   other_data
------------------
2     foo
2     goo
2     hoo

id,   other_data
------------------
3     woo
3     eoo
3     roo

id,   other_data
------------------
5     boo
5     noo
5     moo

etc.

我应该使用什么样的查询?

1 个答案:

答案 0 :(得分:1)

您可以使用带有多个select语句的存储过程来实现它。

您的存储过程应如下所示:

CREATE PROCEDURE YourSPName
    (
     --Write your parameters here if any
     @Selected_id INT)
AS
BEGIN
    DECLARE @MyIDs TABLE (ID INT, isProcessed BIT)
    DECLARE @CurrentID INT

    --Holds all IDs from your table
    INSERT INTO @MyIDs
    SELECT DISTINCT ID, 0 FROM Other_Table WHERE other_id = @Selected_id

    --Loop until all IDs are processed
    WHILE EXISTS(SELECT NULL FROM @MyIDs WHERE isProcessed = 0)
    BEGIN
        --fetch the topmost unprocessed ID
        SELECT TOP 1 @CurrentID = ID
        FROM @MyIDs
        WHERE isProcessed = 0

        --Your query goes here
        SELECT id, other_data 
        FROM Data_Table
        WHERE id = @CurrentID

        --Set the processed status on the same record
        UPDATE @MyIDs
        SET isProcessed = 1
        WHERE ID = @CurrentID
    END

END

而且,您应该像这样编写代码:

var conn = new SqlConnection("Connection String");
var command = new SqlCommand();

var sqlDataAdapter = new SqlDataAdapter();
var dataSet = new DataSet();

command = new SqlCommand("YourSPName", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Selected_id", id); // Your parameters will be added like this, if there are no parameters, remove this line

sqlDataAdapter = new SqlDataAdapter(command);
sqlDataAdapter.Fill(dataSet);

conn.Close();

现在,您可以使用dataSet.Tables[index]来引用从存储过程返回的任何数据表。 e.g。

dataSet.Tables[0]
dataSet.Tables[1]