【问题标题】:While loop in stored procedure [closed]存储过程中的while循环[关闭]
【发布时间】:2013-08-02 07:22:19
【问题描述】:

这是我的第一张桌子

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

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

【问题讨论】:

  • 我想在 C# 中使用存储过程
  • @punter 为什么您想在 C# 中执行此操作?或使用while 循环?甚至使用存储过程?这只是一个基于 1 行集合的 insert 语句,不是吗?
  • @MarcGravell 这只是我实际需求的一个示例。
  • 那你能给出你的实际要求吗?给出一个可以用更直接的方式轻松解决的问题往往不会为您的实际需求提供有用的答案。

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


【解决方案1】:

怎么样

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

【讨论】:

    【解决方案2】:

    在您的数据库中创建一个存储过程(对于主体,我使用了来自@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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多