While在存储过程中循环
本文关键字:过程中 循环 存储过程 存储 While | 更新日期: 2023-09-27 18:25:51
这是我的第一张表
表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"])
}
}
如何使用存储过程来完成此操作?
像这样的东西怎么样
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
在数据库中创建一个存储过程(对于主体,我使用了@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();
}
}