在存储过程中循环

时间:2013-08-02 07:22:20

标签: c# sql sql-server stored-procedures

这是我的第一张表

表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"])
         }
}

如何使用存储过程执行此操作?

2 个答案:

答案 0 :(得分: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   t1.TenderNumber=@TenderNumber

答案 1 :(得分: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   t1.TenderNumber=@TenderNumber
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();
    }
}