I'm pretty new to Microsoft T-sql (Use to Oracle PL/SQL) and I ran into a annoying problem with a very simple procedure.
I created the following procedure
CREATE PROCEDURE [dbo].[ele_test] #productId INT
AS
DECLARE #productCode VARCHAR(100);
DECLARE #productDescription VARCHAR(100);
DECLARE #error VARCHAR(100);
--Fetch product
IF #productId != NULL
BEGIN
SELECT #productCode = ProductCode
,#productDescription = ProductDescription
FROM d_afterpay.dbo.Product
WHERE ProductId = #productId
END
IF ##ROWCOUNT = 0
BEGIN
SET #error = 'Product not found: ' + cast(#productId AS VARCHAR(19))
RAISERROR (#error,16,1);
END
And when I run it this way:
exec ele_test 5
I get:
Msg 50000, Level 16, State 1, Procedure ele_test, Line 20
Product not found. Productid : 5
Yet when I run just the query like this:
SELECT * FROM d_afterpay.dbo.Product
WHERE ProductId = 5
I do get a proper result...
Any idea what I am doing wrong?
Your query syntax is slightly wrong, change the query to read:
IF (#productId IS NOT NULL)
instead of using !=
This meant your SELECT statement was never being called hence why the product was always missing.
Related
I have this stored procedure:
create proc Sponsors.GetLightBoxAd
(
#SponsorID varchar(30),
#ADIDOut varchar(30) OUTPUT,
#UserID varchar(30),
#ProjectID varchar(50),
#PlatformID int
)
as
begin
SELECT TOP 1 #ADIDOut = AD.ADID --my output. AD.ADID is a varchar(30) column
FROM Sponsors.AD
WHERE AD.Active = 1 and AD.SponsorID = #SponsorID
ORDER by NEWID() -- I want the first one picked at random
IF ISNULL(#ADIDOut,-1) != -1 --if the result set wasn't null, run some update queries with the result
BEGIN --These queries do not have output variables.
EXEC Sponsors.proc1 #ADIDOut, #SponsorID
EXEC Projects.proc2 #ProjectID,#ADIDOut,#UserID,#PlatformID
END --end the if
end --end the proc
go
This should return either a null value or a varchar.
However when I try to execute the query, SSMS auto-generates this code for me to run the query:
USE [MyDB]
GO
DECLARE #return_value int, --Why is this here???
#ADIDOut varchar(30) -- this should be my only output
EXEC #return_value = [Sponsors].[GetLightBoxAd]
#SponsorID = N'Alienware',
#ADIDOut = #ADIDOut OUTPUT,
#UserID = N'127.0.0.1',
#ProjectID = N'TestProject',
#PlatformID = 1
SELECT #ADIDOut as N'#ADIDOut'
SELECT 'Return Value' = #return_value --why is this here?
GO
And then it gives me an error because it appears to try to convert the result of ADIDOut into an int... Why is there an int #Return_Value variable and why is it trying to put my actual OUTPUT result into it?
The error was in this line:
IF ISNULL(#ADIDOut,-1) != -1
It seems since I put just -1 without quotes as the comparison, sql reads this as an integer and cannot compare it to a nullable string so the error is raised. Putting the -1's into quotes fixes the error and the query runs. Thanks for the help!
Please how can display the number of rows inserted into an archive table using Microsoft SQL server 2012 with Stored Procedure. I have my code display below. I ran the code successful, but calling the stored procedure, I got error message says
Msg 8114, Level 16, State 5
Procedure p_moveTransHisttoArchive3a, Line 0 Error converting data type varchar to datetime.
Here is my code:
IF OBJECT_ID(N'Production.p_moveTransHisttoArchive3a', N'P') IS NOT NULL
DROP PROCEDURE Production.p_moveTransHisttoArchive3a;
GO
CREATE PROCEDURE Production.p_moveTransHisttoArchive3a
#FiveDaysAgo DATETIME
AS
SET NOCOUNT ON;
BEGIN
DECLARE #counter INT;
SET #counter = ##ROWCOUNT
INSERT INTO Production.TransactionHistoryArchive
SELECT*
FROM Production.TransactionHistory
WHERE TransactionDate <= #FiveDaysAgo
RETURN #counter --No of rows moved
END;
GO
Here is something close to what you want I think. Why is your inbound parameter named FiveDaysAgo? If you want to always get rows that are older than five days ago that belongs INSIDE the proc, not as a parameter.
CREATE PROCEDURE Production.p_moveTransHisttoArchive3a
#FiveDaysAgo DATETIME
, #RowCount int OUTPUT
AS
set nocount on;
INSERT INTO Production.TransactionHistoryArchive
(
Col1
, Col2
)
SELECT Col1
, Col2
FROM Production.TransactionHistory
WHERE TransactionDate <= #FiveDaysAgo
select #RowCount = ##ROWCOUNT
I have a stored procedure for insert operation.I tried the following but it gives me error.
ALTER PROCEDURE SetStaffSalary
#staffid int =0,
#amount int = 0
AS
SET NOCOUNT ON
BEGIN
begin
insert into AccStaff (totalSalary) values (#amount) where fk_staffID = #staffid;
end
END
gives error incorrect syntax near the keyword where.
there's no "where" on insert syntax.
example :
insert into account (staffid, salary) values (#id, #salary);
or you could use update syntax to update the data.
update account set salary = #salary where staffid = #id;
try it like this - it looks like you want t do update
ALTER PROCEDURE setstaffsalary #staffid int = 0 ,
#amount int = 0
AS
BEGIN
UPDATE accstaff
SET totalsalary = #amount
WHERE fk_staffid
=
#staffid;
END;
I want to use SQL Server 2014 stored procedure in Report Builder.
ALTER PROCEDURE [dbo].[getCharacterDetails]
#id int
,#name VARCHAR(200) = '' OUTPUT
,#level int = 0 OUTPUT
AS
BEGIN
SELECT
#name = name, #level = level
FROM
dbo.Characters
WHERE
id = #id;
RETURN
END
I want to use #id as an input parameter and name and level as output only parameters.
When I call the procedure using Report Builder I get no data.
When I execute a query:
exec [dbo].[getCharacterDetails] #id= 1;
I also get no result values, only (1 row(s) affected) or Commands completed successfully.
The table Characters contains 1 row with id=1, so the select is correct.
Am I doing it right? Should I be using stored procedures or maybe UDF?
I'm new to SQL Server.
No, this stored procedure definitely doesn't return rows - because you're capturing the values into output parameters.
If you want to return rows - do not assign those columns to variables! Just write the select"as is".
So just this this SELECT statement instead:
SELECT
name, level
FROM
dbo.Characters
WHERE
id = #id;
and your stored procedure will now return a result set of data.
Try this:
ALTER PROCEDURE [dbo].[getCharacterDetails]
#id int
,#name VARCHAR(200) = '' OUTPUT
,#level int = 0 OUTPUT
AS
BEGIN
SELECT
name, level
FROM
dbo.Characters
WHERE
id = #id;
RETURN
END
Try running the stored procedure as:
declare #name VARCHAR(200);
declare #level int;
exec dbo.getCharacterDetails 1, #name output, #level output;
select #name, #level;
You have to provide the arguments and then look at them afterwards. That is how output parameters work.
If you want the stored procedure to return rows, then don't assign the values, or you can do both. The body could be:
SELECT #name = name, #level = level
FROM dbo.Characters
WHERE id = #id;
SELECT #name, #level;
And, for such a simple process, you might want just a view or user defined function.
Your data is cached, delete the data file (rdl.data) it's in the same folder your rdl is in
The name and level parameters serve no purpose. Remove them.
ALTER PROCEDURE [dbo].[getCharacterDetails]
#id int
AS
BEGIN
SELECT
name, level
FROM
dbo.Characters
WHERE
id = #id;
RETURN
END
call it like this:
EXEC [dbo].[getCharacterDetails] #ID
and make sure you map a SSRS parameter to the input parameter #ID in the parameters tab.
If you still don't get anything use SQL Profiler to work out what parameter it's passing in.
I'm learning sql from a book and I'm trying to write a stored procedure but I don't believe that I'm doing it correctly. Is the following way not valid in Microsoft SQL? If not, when is it valid, if ever?
create procedure dept_count(in dept_name varchar(20), out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
I get the following error
Msg 156, Level 15, State 1, Procedure wine_change, Line 1
Incorrect syntax near the keyword 'in'.
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
#studentid INT, --Input parameter , Studentid of the student
#studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
#StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT #studentname= Firstname+' '+Lastname,
#StudentEmail=email FROM tbl_Students WHERE studentid=#studentid
END
In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:
CREATE PROCEDURE dept_count
(
-- Add input and output parameters for the stored procedure here
#dept_name varchar(20), --Input parameter
#d_count int OUTPUT -- Output parameter declared with the help of OUTPUT/OUT keyword
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Statements for procedure here
SELECT #d_count = count(*)
from instructor
where instructor.dept_name=#dept_name
END
GO
and to execute above procedure we can write as:
Declare #dept_name varchar(20), -- Declaring the variable to collect the dept_name
#d_count int -- Declaring the variable to collect the d_count
SET #dept_name = 'Test'
Execute dept_count #dept_name,#d_count output
SELECT #d_count -- "Select" Statement is used to show the output
I think it can help you:
CREATE PROCEDURE DEPT_COUNT
(
#DEPT_NAME VARCHAR(20), -- Input parameter
#D_COUNT INT OUTPUT -- Output parameter
-- Remember parameters begin with "#"
)
AS -- You miss this word in your example
BEGIN
SELECT COUNT(*)
INTO #D_COUNT -- Into a Temp Table (prefix "#")
FROM INSTRUCTOR
WHERE INSTRUCTOR.DEPT_NAME = DEPT_COUNT.DEPT_NAME
END
Then, you can call the SP like this way, for example:
DECLARE #COUNTER INT
EXEC DEPT_COUNT 'DeptName', #COUNTER OUTPUT
SELECT #COUNTER
Try this:
create procedure dept_count(#dept_name varchar(20),#d_count int)
begin
set #d_count=(select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name)
Select #d_count as count
end
Or
create procedure dept_count(#dept_name varchar(20))
begin
select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name
end
CREATE PROCEDURE [dbo].[USP_StudentInformation]
#S_Name VARCHAR(50)
,#S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date VARCHAR(50)
SET #Date = GETDATE()
IF EXISTS (
SELECT *
FROM TB_StdFunction
WHERE S_Name = #S_Name
AND S_Address = #S_Address
)
BEGIN
UPDATE TB_StdFunction
SET S_Name = #S_Name
,S_Address = #S_Address
,ModifiedDate = #Date
WHERE S_Name = #S_Name
AND S_Address = #S_Address
SELECT *
FROM TB_StdFunction
END
ELSE
BEGIN
INSERT INTO TB_StdFunction (
S_Name
,S_Address
,CreatedDate
)
VALUES (
#S_Name
,#S_Address
,#date
)
SELECT *
FROM TB_StdFunction
END
END
Table Name : TB_StdFunction
S_No INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)
Create this way.
Create procedure dept_count(dept_name varchar(20),d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
try this:
create procedure dept_count( #dept_name varchar(20), #d_count INTEGER out)
AS
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
To Create SQL server Store procedure in SQL server management studio
Expand your database
Expand programmatically
Right-click on Stored-procedure and Select "new Stored Procedure"
Now, Write your Store procedure, for example, it can be something like below
USE DatabaseName;
GO
CREATE PROCEDURE ProcedureName
#LastName nvarchar(50),
#FirstName nvarchar(50)
AS
SET NOCOUNT ON;
//Your SQL query here, like
Select FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = #FirstName AND LastName = #LastName
GO
Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (#LastName and #FirstName) and type = parameter type example nvarchar(50) etc.
Source: Stored procedure in sql server (With Example)
To Execute the above stored procedure you can use sample query as below
EXECUTE ProcedureName #FirstName = N'Pilar', #LastName = N'Ackerman';