sql insert operation in stored procedure - sql-server

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;

Related

Insert Into SomeTable Exec StoredProcedure #Param1 = #param1, #Param2 = 'system' is not calling Stored Procedure

I have a scenario where I need to run a stored procedure individually as well as I need to call from some other stored procedure.
Let me present the scenario: I have 3 stored procedures in sequential call from another one. Like 1st stored procedure is getting called from the application when some raw financial data is being imported; 2nd stored procedure is getting called from 1st stored procedure and in 2nd stored procedure, there is a While loop in which my 3rd stored procedure is getting called.
I am posting here 2nd and 3rd stored procedure code here:
2ND stored procedure code:
If #loopCount > 0
Begin
While(#i <= #loopCount)
Begin
Select #RecoString = '',
#CompanyId = 0,
#UserId = 0
Select #RecoString = MainRecord,
#CompanyId = CompanyId,
#UserId = UsersId
From #RecoData With (Nolock)
Where Id = #i
Order By Id
/* 3rd stored procedure is getting called - IF NO INSERT Statement */
----Exec USP_Temp #IsReco = 1,#ReconcileBy = 'system',#UserCompanyId = #UserCompanyId,#UserId = #UserId,#finalCollection = #RecoString
/* 3rd stored procedure is NOT getting called - IF INSERT Statement */
Insert Into dbo.ReconcileInsertUpdateLog(TransferDetailId,Msg,ReconcilationId,IsFutureTransferReconciled)
Exec dbo.USP_Temp #IsReco = 1, #ReconcileBy = 'system', #CompanyId = #CompanyId, #UserId = #UserId, #finalCollection = #RecoString, #isAutoReconcile = 0
Set #i = #i + 1
End
End
3RD stored procedure code:
ALTER PROCEDURE dbo.USP_Temp
#IsReco Bit
,#ReconcileBy Nvarchar(250)
,#UserCompanyId int
,#UserId int
,#finalCollection Nvarchar(Max) = ''
,#isAutoReconcile Bit = 0
AS
BEGIN
Set Nocount On;
Declare #TransName Varchar(100)
Select #TransName = 'USP_Temp'
Begin Try
Begin Transaction #TransName
Declare #Msg Nvarchar(Max) = ''
,#ParentReconcilationId Int = 0 -- 07.25.2019
,#IsFutureTransferReconciled Int = 0 -- 07.25.2019
------------------------------------------------------------
-- Return result
------------------------------------------------------------
Insert Into dbo.TempReco(Comments)
Select 'Reached to USP_Temp 1 step ahead of Return final Result'
Select 1 As TransferDetailId
,#Msg As Msg
,#ParentReconcilationId As ReconcilationId -- 07.25.2019
,#IsFutureTransferReconciled As IsFutureTransferReconciled -- 07.25.2019
Commit Transaction #TransName
GoTo EndLevel
End Try
Begin Catch
Set #Msg = Error_Message()
GoTo Error
End Catch
Error:
BEGIN
Insert Into dbo.TempReco(Comments) Select 'Reached to USP_Temp - Error Block'
Rollback Transaction #TransName
Select 0 As TransferDetailId
,#Msg As Msg
,0 As ReconcilationId -- 07.25.2019
,0 As IsFutureTransferReconciled -- 07.25.2019
END
EndLevel:
END
GO
Look at the 2nd stored procedure code, I have commented the code which is working if no insert into statement prior to Exec SPName and when calling stored procedure along with insert into SomeTable prior statement then stored procedure is not getting called. Does anyone have some idea on this?

SQL Server: how to generate serial number by dynamic SQL

create procedure test
(#TABLE_NAME varchar(20))
as
declare #lastval varchar(10)
set #lastval = right('000000000' + convert(varchar(10),
(select IsNull(max(Serialno), 0) + 1
from #TABLE_NAME)), 10)
return #lastval
end
Now tell me how I could compose or form dynamic SQL with above SQL where I will pass table name to store procedure when call that stored procedure?
How to return #lastval value to its calling environment?
How to call stored procedure test from another stored procedure where I will store the return value ?
Guide me with sample code.
Genearlly, it's best to use an IDENTITY or a SEQUENCE to assign serial numbers. A zero-padded string or other formatting requirements could be added to the table as a computed column based on the underlying serial integer or formatted in the app code. However, both IDENTITY and SEQUENCE may have gaps, such as due to rollbacks or SQL Server service restart.
In cases where an unbroken sequence of serial values is required by business, one can maintan the last assigned values in a table and assign values transactionally. Below is an example that returns the value using an OUTPUT parameter. Although the proc in your question uses the stored proc RETURN value for this purpose, that should only be used to indicate success or failure, not return data.
CREATE TABLE dbo.TableSerialNumber(
TableName sysname NOT NULL
CONSTRAINT PK_SerialNumber PRIMARY KEY
, SerialNumber int NOT NULL
, FormatString nvarchar(20) NULL
);
GO
INSERT INTO dbo.TableSerialNumber VALUES('Invoice', 0, '0000000000');
INSERT INTO dbo.TableSerialNumber VALUES('PurchaseOrder', 0, '0000000000');
GO
CREATE PROC dbo.GetNextSerialNumberForTable
#TableName sysname
, #FormattedSerialNumber varchar(10) OUTPUT
AS
SET NOCOUNT ON;
DECLARE
#SerialNumber int
, #FormatString nvarchar(20);
UPDATE dbo.TableSerialNumber
SET
#SerialNumber = SerialNumber += 1
, #FormatString = FormatString
WHERE TableName = #TableName;
IF ##ROWCOUNT = 0
RAISERROR('Table %s does not exist in dbo.TableSerialNumber', 16, 1, #TableName);
SET #FormattedSerialNumber = CAST(FORMAT(#SerialNumber, #FormatString) AS varchar(10));
GO
--example usage
CREATE PROC dbo.InsertInvoice
#InvoiceData int
AS
SET XACT_ABORT ON;
DECLARE #InvoiceNumber varchar(10);
BEGIN TRY
BEGIN TRAN;
EXECUTE dbo.GetNextSerialNumberForTable
#TableName = N'Invoice'
, #FormattedSerialNumber = #InvoiceNumber OUTPUT;
INSERT INTO dbo.Invoice (InvoiceID, InvoiceData)
VALUES(#InvoiceNumber, #InvoiceData);
SELECT #InvoiceNumber AS InvoiceNumber;
COMMIT;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
GO

SQL Server: how to create a stored procedure

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';

Microsoft sql stored procedure not executing select statement properly

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.

Efficiently return a value from a stored procedure

I have query which returns single value (i.e) count. I'm exceuting it using the stored procedure in the following way and using execute reader with dataset to get single value
CREATE PROCEDURE GetCnt
#EmpNo char(4)
AS
BEGIN
SET NOCOUNT ON;
Declare #Cnt int
SELECT #Cnt = count(*)
FROM employees
WHERE EMPLNO = #EmpNo
AND test = 'p'
BEGIN
SELECT #Cnt
END
END
is this effcient way
or Do I need to use the execute.scalar() and return value directly from the query instead of assigning to #cnt
can any one advise me
All ExecuteScalar does is get the first field from the first record.
Can't you just SELECT the count directly?
BEGIN
SET NOCOUNT ON
SELECT Count(*) FROM employees WHERE EMPLNO = #EmpNo AND test='p'
END
You do not need to create the variable. You just need the following:
CREATE PROCEDURE GetCnt
#EmpNo char(4)
AS
BEGIN
SET NOCOUNT ON;
SELECT count(1)
FROM employees
WHERE EMPLNO = #EmpNo
AND test = 'p'
END
Since this is only one value being returned from the stored procedure, you will likely want to use ExecuteScalar()

Resources