Understanding simple stored procedure: Moving output to a variable
I'm hoping I can get some help with understanding a simple stored procedure. Basically, I want to store the output of a select statement in a variable and then print out the value of the variable.
I found a very similar question here: Simple Stored Procedure Question
And the code looks as follows:
CREATE PROCEDURE ReturnPrice
@carID int,
@price decimal(18,2) output
AS
SELECT
@price = Price
FROM
dbo.Cars
WHERE
CarID = @carID
My question is this: How do I get the value of @carID?
If I try this:
declare @carOutput varchar(50)
exec carInformation, '@carOutput varchar(50) output', 开发者_Go百科 @carOutput output
I get an error of:
Msg 170, Level 15, State 1, Line 3
Line 3: Incorrect syntax near ','.
Thank you!
exec carInformation, '@carOutput varchar(50) output', @carOutput output
^bad
exec carInformation '@carOutput varchar(50) output', @carOutput output
^good
but also '@carOutput varchar(50) output'
must be an int, but you are passing in a string
you need to have the calling application already know the value for @carID, and the procedure uses that value to return the price.
so try something like:
DECLARE @CarID_x int
,@Price_x decimal(18,2)
SET @CarID_x=123
EXEC ReturnPrice @CarID, @Price_x OUTPUT
PRINT @Price_x
or
DECLARE @Price_x decimal(18,2)
EXEC ReturnPrice 123, @Price_x OUTPUT
PRINT @Price_x
both code examples above will return the Price
column value for the dbo.Cars
row that has the CarID
value of 123
.
If you don't know the CarID
then run:
SELECT
CarID, Price
FROM dbo.Cars
and you will get a result set containing all the prices for all the cars.
精彩评论