如何使用包含两个查询的 SqlCommand



第一个问题,我想在一个命令中实现两个查询。

我应该遵循的正确语法是什么?

我试过这个

SqlCommand cmd = new SqlCommand("BEGIN;" +
" INSERT INTO Booking(Arrive, leave, RoomId)" +
" VALUES(@Arrive, @leave, @RoomId);" +
" INSERT INTO Customer(CustomerId, CustomerName, birth_day, City, Phone, Email, Gender)" +
" VALUES(@CustomerId, @CustomerName, @birthday, @City, @Phone, @Email, @Gender); COMMIT; ", con)

第二个:我可以在SqlCommand之前加上"if语句"吗?

例如:

if (x = 1) 
{
SqlCommand cmd = new SqlCommand("BEGIN;" +
" INSERT INTO Booking(Arrive, leave, RoomId)" +
" VALUES(@Arrive, @leave, @RoomId);" +
" INSERT INTO Customer(CustomerId, CustomerName, birth_day, City, Phone, Email,Gender)" +
" VALUES(@CustomerId, @CustomerName, @birthday, @City, @Phone, @Email, @Gender);COMMIT; ", con)
}
else
{ 
SqlCommand cmd = new SqlCommand("insert into Customer(CustomerId, CustomerName, birth_day, City, Phone, Email, Gender)" +
" values(@CustomerId, @CustomerName, @birthday, @City, @Phone, @Email, @Gender)", con)
}

是的,您可以使用存储过程并调用其中的任意数量的查询。

是的,您可以使用 if 语句,但它应该是if(x == 1

我认为您的查询也应该有效,不需要begincommit

最新更新