我有个问题。这是我第一次尝试在SQL Server中编写与SELECT
和INSERT
不同的东西。我无法解决问题。
我有这个触发器
ALTER TRIGGER [dbo].[createTaxes] ON [dbo].[Customers]
AFTER INSERT AS
BEGIN
DECLARE @dayly varchar(10),
@weekly varchar(10),
@mountly varchar(10),
@CustomerID int;
SET @dayly = 'SELECT cast(daily as smallmoney) FROM Rates WHERE id = 1 '
SET @weekly = 'SELECT cast(weekly as smallmoney) FROM Rates WHERE id = 1'
SET @mountly = 'SELECT cast(mountly as smallmoney) FROM Rates WHERE id = 1'
SET @CustomerID ='SELECT CONVERT(INT, CustomerID) FROM INSERTED'
INSERT INTO RentalRates(CustomerId, Daily, Monthly, Weekly)
VALUES ('SELECT CAST(@CustomerID AS int)', 'SELECT CAST(@dayly AS smallmoney)',
'SELECT CAST(@mountly AS smallmoney)', 'SELECT CAST(@weekly AS smallmoney)');
END
我尝试了很多组合,但它不起作用:(
目前错误是
将varchar值'SELECT CONVERT(INT,CustomerID)FROM INSERTED'转换为数据类型int时转换失败。
提前感谢浪费时间。
我无法理解为什么转换不起作用?我需要做些什么才能正确转换它。
这里有两个问题
您使用的变量只能包含单个值,而INSERTED实际上是一组零,一个或多个记录,并且您希望为每个记录插入租赁费率
更糟糕的是,您将查询文本分配给它们而不是查询结果
SET @CustomerID ='SELECT CONVERT(INT, CustomerID) FROM INSERTED'
代替
SET @CustomerID =(SELECT CONVERT(INT, CustomerID) FROM INSERTED)
这就是为什么你得到你看到的错误。您正在尝试将@customerID的值设置为45个字符的长字符串'SELECT CONVERT(INT,CustomerID)FROM INSERTED'
如果您一次只添加一条记录,那么将该变量和其他变量排序可能会有效,但实际上您应该完全丢失变量。
您的INSERT语句应该是这样的
INSERT INTO RentalRates(CustomerId,Daily,Monthly,Weekly)
CONVERT(INT, i.CustomerID),
cast(r.daily as smallmoney),
cast(r.weekly as smallmoney) ,
cast(r.mountly as smallmoney)
FROM INSERTED i
JOIN Rates r ON r.id = 1