我有一个像这样连接的数据库。
我正在编写一个WPF应用程序来对表进行简单的插入/删除/更新。
问题是这样的:
我收到一个广告对象,并尝试将其插入到数据库
中public static int Insert(Advertisement Advertisement)
{
Database db = new Database();
db.Connect();
SqlCommand command = db.CreateCommand(SQL_INSERT);
PrepareCommand(command, Advertisement);
int ret = db.ExecuteNonQuery(command);
db.Close();
return ret;
}
SQL_INSERT
public static String SQL_INSERT = "INSERT INTO \"Advertisement\" VALUES (@IDProduct," +
" @CampaignDescription, @CampaignStart, @CampaignEnd)";
IDAdvertisement是一个IDENTITY。
我在广告表INSERT
上设置了触发器ALTER trigger [dbo].[AutomaticUserAdvertisementScoreCalculating]
ON [dbo].[Advertisement]
AFTER INSERT
AS
begin
begin transaction;
declare Users cursor for
Select "User".IDUser, Sum(Price), inserted.IDProduct from "User"
join Purchase as pu on "User".IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join Product as pr on pp.IDProduct = pr.IDProduct
join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType from Product
join Advertisement on Product.IDProduct = Advertisement.IDProduct
join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
GROUP BY "User".IDUser, inserted.IDProduct
HAVING Sum(Price) > 50;
declare @IDUser int;
declare @Price decimal;
declare @IDProduct int;
open Users;
fetch next from Users into @IDUser,@Price, @IDProduct;
while @@FETCH_STATUS=0
begin
insert into UserAdvertisementScore values(@IDUser, (select IDAdvertisement from Advertisement where IDProduct = @IDProduct), @Price);
fetch next from Users into @IDUser, @Price, @IDProduct;
end
close Users;
deallocate Users;
commit;
端
我不知道为什么,但根据使用的IDProduct,它可能会抛出此错误。
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。 声明已经终止。
如果您需要更多信息,请告诉我
答案 0 :(得分:1)
我觉得这确实是重复的。当然错误是一回事,但这个问题的真正问题在于触发器存在严重缺陷。很确定你的整个触发器体可以简化为非常接近这个的东西。而且你不应该在触发器中使用事务。已经有一个正在进行的交易,您所做的任何事情都会导致原始交易失败。
insert UserAdvertisementScore
( --or whatever the column names are. You should ALWAYS specify the columns for an insert
[User]
, Price
, IDProduct
)
Select u.IDUser
, Sum(Price)
, i.IDProduct
from [User] u
join Purchase as pu on u.IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join inserted i on pr.IDProduct = i.IDProduct
join Product as pr on pp.IDProduct = pr.IDProduct
GROUP BY u.IDUser
, i.IDProduct