I know this is a basic question – but I can’t figure the correct way to get this done.
I need to pass a variable to a SQL Server 2008 stored procedure and return the query.
Here’s the stored procedure:
CREATE PROCEDURE pOrders
AS
DECLARE @enteredClientID varchar(20);
DECLARE @Results table (ClientID varchar(20), Num_orders int);
BEGIN
SET NOCOUNT ON;
-- Get all the order from the client
INSERT INTO @Results
SELECT ClientID, sum(Num_orders)
FROM Orders O
WHERE O.ClientID = @enteredClientID
GROUP BY O.ClientID);
-- Insert the orders into the results table --
SELECT *
FROM @Results;
END
GO;
Now, I would execute the stored procedure and get the result back:
exec pOrders
set @enteredClientID = 'ABC123456789'
I get this error message back:
Must declare the scalar variable “@enteredClientID”.
But, I’m declaring the variable…. what am I missing?
You didn’t declare a parameter, but a local variable. To declare it as you wanted to:
An to call it:
or simply