Question

I have a problem. This is my first attempt at writing something different than SELECT and INSERT in SQL Server. And I can't resolve the problem.

I have this trigger

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

I tried many combinations but it doesn't works :(

At the moment the error is

Conversion failed when converting the varchar value 'SELECT CONVERT(INT, CustomerID) FROM INSERTED' to data type int.

Thanks in advance for the wasted time.

I can't understand why the conversion doesn't work? And what I have to do to convert it right.

Was it helpful?

Solution

There are two issues here

You're using variables which can only contain single values while INSERTED is actually a set of zero, one or more records and you want to insert a rental rate for each of them

And to make matters worse you're assigning query text to them as opposed to query results

 SET @CustomerID ='SELECT CONVERT(INT, CustomerID) FROM INSERTED' 

instead of

 SET @CustomerID =(SELECT CONVERT(INT, CustomerID) FROM INSERTED) 

Which is why you're getting the error you see. You're attempting to set the value of @customerID to the 45 character long string 'SELECT CONVERT(INT, CustomerID) FROM INSERTED'

Sorting that and the other variables out might work, if you only add one record at a time, but really you should lose the variables entirely.

Your INSERT statement should be something like this

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top