-3

这是我的第一张桌子

表 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#SubCatID存储并CatID进入新表。这些值将仅从以下方式检索: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"])
         }
}

我如何使用存储过程来做到这一点?

4

2 回答 2

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
于 2013-08-02T07:30:00.300 回答
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();
    }
}
于 2013-08-02T08:48:26.027 回答