2013-08-02 161 views
-2

這是我的第一個表While循環存儲過程

表1

CatID TenderNumber 
    1  AA01012013 
    2  AA01012013 
    3  AA01012013 

表2

SubCatID CatID 
1   1 
2   1 
3   2 
4   2 
5   2 
6   3 

所以這是我的數據庫看起來像。現在我想使用C#SubCatIDCatID存儲到新表中。這些值將從TenderNumber僅作如下檢索:

Select CatID from Table1 where TenderNumber='AA01012013' 

while(SQLDataReader1.read()) 
{ 
     select SubCatID from Table2 where CatID=Reader1["CatID"] 
     While(SQLDataReader2.read()) 
     { 
       insert into Table3(SubCatID,CatID)Values(Reader2["SubCatID"],Reader1["CatID"]) 
     } 
} 

我怎樣才能做到這一點使用存儲過程?

+0

我想在C#中使用存儲過程執行此操作 – punter

+2

@punter **爲什麼要在C#中執行此操作?或者用'while'循環?甚至是存儲過程?這只是一個單行的基於set的'insert'語句,不是? –

+0

@MarcGravell這只是我實際需求的一個示例。 – punter

回答

2

如何像

INSERT INTO Table3 
SELECT t2.SubCatID, 
     t2.CatID 
FROm Table1 t1 INNER JOIN 
     Table2 t2 ON t1.CatID = t2.CatID 
WHERE t1.TenderNumber='AA01012013' 

甚至使用參數,像

DECLARE @TenderNumber VARCHAR(50) = 'AA01012013' 

INSERT INTO Table3 
SELECT t2.SubCatID, 
     t2.CatID 
FROm Table1 t1 INNER JOIN 
     Table2 t2 ON t1.CatID = t2.CatID 
WHERE [email protected] 
0

在你的數據庫中創建一個存儲過程(對身體我用從@astander代碼:)):

CREATE PROCEDURE dbo.p_InsertTenderInfo_byTenderNumber @TenderNumber VARCHAR(50) 
AS 
BEGIN 
    INSERT INTO Table3 
    SELECT t2.SubCatID, 
      t2.CatID 
    FROm Table1 t1 INNER JOIN 
      Table2 t2 ON t1.CatID = t2.CatID 
    WHERE [email protected] 
END 

而在你的C#代碼:

using (var conection = new SqlConnection("conString")) 
{ 
    using (var command = new SqlCommand()) 
    { 
     command.Connection = conection; 
     command.CommandType = System.Data.CommandType.StoredProcedure; 
     command.CommandText = "dbo.p_InsertTenderInfo_byTenderNumber"; 
     command.Parameters.Add(new SqlParameter("@TenderNumber", "AA01012013")); 
     conection.Open(); 
     command.ExecuteNonQuery(); 
     conection.Close(); 
    } 
}