Create a stored procedure to insert new data into a table - sql

I want to create a stored procedure to insert a new row in a table 'dbo.Terms'
CREATE PROCEDURE dbo.terms
#Term_en NVARCHAR(50) = NULL ,
#Createdate DATETIME = NULL ,
#Writer NVARCHAR(50) = NULL ,
#Term_Subdomain NVARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.terms
(
Term_en ,
Createdate ,
Writer ,
Term_Subdomain
)
VALUES
(
#Term_en = 'Cat' ,
#Createdate = '2013-12-12' ,
#Writer = 'Fadi' ,
#Term_Subdomain = 'English'
)
END
GO
But is shows me an error here ( #Term_en = 'Cat') incorrect syntax
Any help?

I presume you want to insert the values cat etc into the table; to do that you need to use the values from your procedures variables. I wouldn't call your procedure the same name as your table it will get all kinds of confusing; you can find some good resources for naming standards (or crib from Adventureworks)
CREATE PROCEDURE dbo.terms
#Term_en NVARCHAR(50) = NULL ,
#Createdate DATETIME = NULL ,
#Writer NVARCHAR(50) = NULL ,
#Term_Subdomain NVARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.terms
(
Term_en ,
Createdate ,
Writer ,
Term_Subdomain
)
VALUES
(
#Term_en,
#Createdate,
#Writer,
#Term_Subdomain
)
END
GO
And to test it
exec dbo.terms
#Term_en = 'Cat' ,
#Createdate = '2013-12-12' ,
#Writer = 'Fadi' ,
#Term_Subdomain = 'English'

Here is how to set your defaults for parameters in your proc:
CREATE PROCEDURE dbo.terms
#Term_en NVARCHAR(50) = 'Cat',
#Createdate DATETIME = '2013-12-12',
#Writer NVARCHAR(50) = 'Fadi',
#Term_Subdomain NVARCHAR(50) = 'English'
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.terms
(
Term_en ,
Createdate ,
Writer ,
Term_Subdomain
)
VALUES
(
#Term_en,
#Createdate,
#Writer,
#Term_Subdomain
)
END
GO

Your code is not correct.
You put value in insert part. You should enter value in execution part
CREATE PROCEDURE dbo.terms
#Term_en NVARCHAR(50) = NULL ,
#Createdate DATETIME = NULL ,
#Writer NVARCHAR(50) = NULL ,
#Term_Subdomain NVARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.terms
(
Term_en,
Createdate,
Writer,
Term_Subdomain
)
VALUES
(
#Term_en ,
#Createdate ,
#Writer ,
#Term_Subdomain
)
END
execute by this
exec dbo.terms
#Term_en = 'Cat' ,
#Createdate = '2013-12-12' ,
#Writer = 'Fadi' ,
#Term_Subdomain = 'English'
GO

-- =============================================
-- Author: xxxx
-- Create date: xx-xx-xxxx
-- Description: Procedure for Inserting Data in table
-- =============================================
CREATE PROCEDURE [dbo].[SP_Emp_Insert]
(
#Empname nvarchar(250)=null,
#Status int=null,
#LoginUserId nvarchar(50)=null,
#Msg nvarchar(MAX)=null OUTPUT
)
AS
BEGIN TRY
INSERT INTO tbl_Employee
VALUES
(
#Empname ,
#Status,
GETDATE(),
GETDATE(),
#LoginUserId
)
SET #Msg='Table Detail Saved Successfully.'
END TRY
BEGIN CATCH
SET #Msg=ERROR_MESSAGE()
END CATCH
GO

Related

How to create a trigger in SQL Server that insert values into two tables using an ID stored in the second one

I have three tables:
RawValues that contains Timestamp, Part, PartNumber,ValueKind, ... , Value
Measurements that contains TimeStamp, ID, Value.
Hashtable that contains ID, Part, ValueKind, ...
I have a stream of data that come into RawValue that I cannot modify. It contains all the columns except the ID.
I want to create a trigger on RawValues that insert the values into Hashtable (if they do not yet exist), select the id from Hashtable and then insert the row into Measurements.
This is what I've created:
CREATE TRIGGER [dbo].[TrigInsertToMeasurements]
ON [dbo].[MeasurementsTemp]
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- Dichiaro le variaibili --
DECLARE
#TimeStamp datetime,
#MachineType char(10),
#MachineModel char(10),
#MachineNumber int,
#Part char(10),
#PartNumber int,
#ValueKind char(10),
#Value float,
#ID int
-- Assegno i valori --
SELECT
#TimeStamp = TimeStamp,
#MachineType = MachineType,
#MachineModel = MachineModel,
#MachineNumber = MachineNumber,
#Part = Part,
#PartNumber = PartNumber,
#ValueKind = ValueKind,
#Value = Value
FROM
inserted
SELECT #ID=ID FROM [dbo].[Hashtable]
WHERE
#MachineType = [MachineType] AND
#MachineModel = [MachineModel] AND
#MachineNumber = MachineNumber AND
#Part = Part AND
#PartNumber = PartNumber AND
#ValueKind = ValueKind
IF count(#ID) = count(#TimeStamp)
BEGIN
INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] ) VALUES (#TimeStamp, #ID, #Value)
END
ELSE BEGIN
BEGIN
IF NOT EXISTS (SELECT [ID] FROM [dbo].[Hashtable] WHERE
#MachineType = [MachineType] AND
#MachineModel = [MachineModel] AND
#MachineNumber = MachineNumber AND
#Part = Part AND
#PartNumber = PartNumber AND
#ValueKind = ValueKind)
BEGIN
INSERT INTO [dbo].[Hashtable] (MachineType, MachineModel, MachineNumber, Part, PartNumber, ValueKind)
VALUES (#MachineType, #MachineModel, #MachineNumber, #Part, #PartNumber, #ValueKind)
END
END
SELECT #ID=ID FROM [dbo].[Hashtable]
WHERE
#MachineType = MachineType AND
#MachineModel = MachineModel AND
#MachineNumber = MachineNumber AND
#Part = Part AND
#PartNumber = PartNumber AND
#ValueKind = ValueKind
INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] ) VALUES (#TimeStamp, #ID, #Value)
END
END
GO
ALTER TABLE [dbo].[MeasurementsTemp] ENABLE TRIGGER [TrigInsertToMeasurements]
GO
The trigger works correctly but sometime in the stream comes rows in groups, then in this case not all the rows are considered.
What can I do? Maybe use a for loop and then access to the arrays? How to do it?
i try to re-code your trigger, replacing it accordinlgy best to my understanding of the logic
CREATE TRIGGER [dbo].[TrigInsertToMeasurements]
ON [dbo].[MeasurementsTemp]
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- Dichiaro le variaibili --
DECLARE
#TimeStamp datetime,
#MachineType char(10),
#MachineModel char(10),
#MachineNumber int,
#Part char(10),
#PartNumber int,
#ValueKind char(10),
#Value float,
#ID int
-- Assegno i valori --
--SELECT
-- #TimeStamp = TimeStamp,
-- #MachineType = MachineType,
-- #MachineModel = MachineModel,
-- #MachineNumber = MachineNumber,
-- #Part = Part,
-- #PartNumber = PartNumber,
-- #ValueKind = ValueKind,
-- #Value = Value
--FROM
-- inserted
--SELECT #ID=ID FROM [dbo].[Hashtable]
--WHERE
-- #MachineType = [MachineType] AND
-- #MachineModel = [MachineModel] AND
-- #MachineNumber = MachineNumber AND
-- #Part = Part AND
-- #PartNumber = PartNumber AND
-- #ValueKind = ValueKind
IF count(#ID) = count(#TimeStamp)
BEGIN
--INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] ) VALUES (#TimeStamp, #ID, #Value)
INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] )
SELECT i.TimeStamp, h.ID, i.Value
FROM inserted i
INNER JOIN [dbo].[Hashtable] h ON i.[MachineType] = h.[MachineType]
AND i.[MachineModel] = h.[MachineModel]
AND i.MachineNumber = h.MachineNumber
AND i.Part = h.Part
AND i.PartNumber = h.PartNumber
AND i.ValueKind = h.ValueKind
WHERE i.TimeStamp IS NOT NULL
END
ELSE
BEGIN
-- BEGIN
--IF NOT EXISTS (SELECT [ID] FROM [dbo].[Hashtable] WHERE
-- #MachineType = [MachineType] AND
-- #MachineModel = [MachineModel] AND
-- #MachineNumber = MachineNumber AND
-- #Part = Part AND
-- #PartNumber = PartNumber AND
-- #ValueKind = ValueKind)
-- BEGIN
-- INSERT INTO [dbo].[Hashtable] (MachineType, MachineModel, MachineNumber, Part, PartNumber, ValueKind)
-- VALUES (#MachineType, #MachineModel, #MachineNumber, #Part, #PartNumber, #ValueKind)
-- END
-- END
INSERT INTO [dbo].[Hashtable] (MachineType, MachineModel, MachineNumber, Part, PartNumber, ValueKind)
SELECT i.MachineType, i.MachineModel, i.MachineNumber, i.Part, i.PartNumber, i.ValueKind
FROM inserted i
WHERE NOT EXISTS
(
SELECT *
FROM [dbo].[Hashtable] x
WHERE x.MachineType = i.MachineType
AND x.MachineModel = i.MachineModel
AND x.MachineNumber = i.MachineNumber
AND x.Part = i.Part
AND x.PartNumber = i.PartNumber
AND x.ValueKind = i.ValueKind
)
--SELECT #ID=ID FROM [dbo].[Hashtable]
--WHERE
-- #MachineType = MachineType AND
-- #MachineModel = MachineModel AND
-- #MachineNumber = MachineNumber AND
-- #Part = Part AND
-- #PartNumber = PartNumber AND
-- #ValueKind = ValueKind
-- INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] ) VALUES (#TimeStamp, #ID, #Value)
INSERT INTO [dbo].[Measurements] ([TimeStamp], [ID], [Value] )
SELECT i.[TimeStamp], h.ID, i.Value
FROM inserted i
INNER JOIN [dbo].[Hashtable] h ON i.MachineType = h.MachineType
AND i.MachineModel = h.MachineModel
AND i.MachineNumber = h.MachineNumber
AND i.Part = h.Part
AND i.PartNumber = h.PartNumber
AND i.ValueKind = h.ValueKind
END
END

Not able to get the stored procedure's result in variable?

i have a Hierarchy of stored procedures calling one in another as below:
1
2
3
Now what i am doing is:
first of all i am showing the 3rd level sp which is least level.
CREATE proc [dbo].[proc_tblUserScheduleNewUpdateOnly]
(
#Scheduleid bigint=258,
#Contactid uniqueidentifier='EDE3E474-02CA-49C7-86DD-AA97794ECF8A',
#ScheduleDate datetime= '2012-07-16 00:00:00.000',
#StartTime varchar(20)='12:03:00.0000000',
#EndTime varchar(20)='15:00:00.0000000',
#Location bigint=8,
#Area bigint=7,
#Room bigint=9,
#Enddate datetime='2012-07-16 00:00:00.000',
#CurrentTime Datetime='2012-07-16 12:00:35.900',
#ModifiedBy uniqueidentifier='0BF84A77-FAC2-44E5-AF9B-39740415DBD2',
#schedulefileidNew bigint=''
)
as
Declare #schedulefileid bigint
if #schedulefileidNew=0
begin
set #schedulefileid=null
end
else
begin
set #schedulefileid=#schedulefileidNew
end
update tblUserScheduleNew set Contactid=#Contactid,
ScheduleDate =#ScheduleDate,
StartTime = #StartTime,
EndTime =#EndTime,
Location =#Location,
Area=#Area,
Room =#Room,
LastModifiedDate=#CurrentTime ,EndDate=#Enddate,
ModifiedBy=#ModifiedBy,
ScheduleFileId=#schedulefileid
where ScheduleId=#Scheduleid and IsDeleted=0 and isActive=1
select 1
Now the second level :
CREATE Proc [dbo].[proc_tblUserScheduleNewFutureUpdate]
(
#StartDatePassed datetime='8/2/2012 12:00:00 AM',
#EndDatePassed datetime='8/2/2012 12:00:00 AM', --='2012-07-11 00:00:00.000',
#StartTimePassed varchar(20)='13:00:00',--='02:00:00.0000000',
#EndTimePassed varchar(20)='21:00:00',--='03:00:00.0000000',
#CurrentDateTime Datetime ='8/1/2012 5:50:31 AM', --='2012-07-11 02:07:35.900'
#Scheduleid bigint=0x0000000000000166,
#Contactid uniqueidentifier='77680636-bc4b-4489-9cec-3bc000ffe773',
#Location bigint=11,
#Area bigint=10,
#Room bigint=11,
#ModifiedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#schedulefileidNew bigint=null
)
as
declare #ResultForInsertUpdate varchar(200);
if CONVERT(date,#StartDatePassed,101)>CONVERT(date,#CurrentDateTime,101) and
CONVERT(date,#EndDatePassed,101)>CONVERT(date,#CurrentDateTime,101) and
CONVERT(date,#EndDatePassed,101)>CONVERT(date,#StartDatePassed,101)
begin -- it will run when the Start date and end date passed are greater than Current date and EndDate is greater than Start date.
Print 'Update'
exec #ResultForInsertUpdate = dbo.proc_tblUserScheduleNewUpdateOnly #Scheduleid,#Contactid,#StartDatePassed,#StartTimePassed,#EndTimePassed,#Location,#Area,#Room,#EndDatePassed,#CurrentDateTime,#ModifiedBy,#schedulefileidNew
select #ResultForInsertUpdate;
end
else
begin
select 2
end
Now the 3rd and final level
Alter Proc proc_tblUserScheduleNewUpdateWithAllRoomsOption
(
#StartDatePassed datetime='2013-04-29 00:00:00.000',
#EndDatePassed datetime='2013-04-29 00:00:00.000',
#StartTimePassed varchar(20)='15:00:00',
#EndTimePassed varchar(20)='20:00:00',
#CurrentDateTime Datetime ='2013-04-25 00:00:00.000',
#Scheduleid bigint=1,
#Contactid uniqueidentifier='FD3E0DDF-8B91-493F-94DF-B8280AC33BC0',
#Location bigint=17,
#Area bigint=0,
#Room bigint=0,
#ModifiedBy uniqueidentifier='ACF7961C-4111-49AD-A66A-CE7F9CE131BD',
#schedulefileidNew bigint=null,
#OldStartDate Datetime='2013-04-26 00:00:00.000',
#OldEndDate DateTime='2013-04-26 00:00:00.000',
#OldStartTime varchar(20)='11:11:11.0000000',
#OldEndTime varchar(20)='22:22:22.0000000',
#OldContactid uniqueidentifier='DA101C1D-45A1-4F9A-B19B-4E88DDE01B10',
#OldLocation bigint=18,
#OldArea bigint=17,
#OldRoom bigint=22
)
as
-- declare variables Starts here
declare #row_count int;
DECLARE #intFlag INT=0;
declare #locationIdForLoop bigint ;
declare #AreaIdForLoop bigint ;
declare #RoomIdForLoop bigint ;
DECLARE #ResultForInsertUpdate INT
set #ResultForInsertUpdate=1;
-- declare tempraroy table to store location, Area and rooms Starts here
CREATE TABLE #tempTable (
RowNum int,
LocationId bigint,
AreaId bigint,
RoomId bigint
)
-- declare tempraroy table to store location, Area and rooms Ends here
if #Area=0 and #Room=0
begin
insert into #tempTable (RowNum,LocationId,AreaId,RoomId) (select ROW_NUMBER() OVER
(ORDER BY LocationId desc) RowNum, LocationId,AreaId,RoomId from
tblroomnew where areaid in(select Areaid from tblareanew where locationid=#Location))
set #row_count=(select count(*) from #tempTable)
SET #intFlag = 1
WHILE (#intFlag <=#row_count)
BEGIN
-- Do what ever you want to do here
set #locationIdForLoop=(select locationid from #tempTable where RowNum=#intFlag)
set #AreaIdForLoop=(select areaid from #tempTable where RowNum=#intFlag)
set #RoomIdForLoop=(select roomid from #tempTable where RowNum=#intFlag)
if #ResultForInsertUpdate=1
begin
if exists(select 1 from tbluserschedulenew where
convert(datetime,ScheduleDate,101)=convert(datetime,#OldStartDate,101) and
Convert(datetime,EndDate,101)=convert(datetime,#OldEndDate,101) and
convert(Time,StartTime,108)=convert(Time,#OldStartTime,108) and
convert(Time,EndTime,108) =convert(Time,#OldEndTime,108) and contactid=#OldContactid
and
Location=#OldLocation and Area=#OldArea and Room=#OldRoom )
begin
Print 'Update First record'
exec #ResultForInsertUpdate = proc_tblUserScheduleNewFutureUpdate #StartDatePassed,#EndDatePassed,#StartTimePassed,#EndTimePassed,#CurrentDateTime,#Scheduleid,#Contactid,
#locationIdForLoop,#AreaIdForLoop,#RoomIdForLoop,#ModifiedBy,#schedulefileidNew
--set #ResultForInsertUpdate=1
print #ResultForInsertUpdate
--select #ResultForInsertUpdate
end
else
begin
print 'insert karna hai record'
exec proc_tblUserScheduleNewLatestInsert #Contactid,#StartDatePassed,#StartTimePassed,#EndTimePassed,
#locationIdForLoop,#AreaIdForLoop,#RoomIdForLoop, #EndDatePassed,#ModifiedBy,0,#CurrentDateTime
--print #ResultForInsertUpdate
end
end
else
begin
select #ResultForInsertUpdate
end
SET #intFlag = #intFlag + 1
END
end
else
begin
if #Area!=0 and #Room=0
begin
insert into #tempTable (RowNum,LocationId,AreaId,RoomId) (select ROW_NUMBER() OVER (ORDER BY LocationId desc) RowNum, LocationId,AreaId,RoomId from
tblroomnew where areaid =#Area)
set #row_count=(select count(*) from #tempTable)
end
else
begin
print 'chalan do jo chal reha'
exec proc_tblUserScheduleNewFutureUpdate #StartDatePassed,#EndDatePassed,#StartTimePassed,#EndTimePassed,#CurrentDateTime,#Scheduleid,#Contactid,
#location,#Area,#Room,#ModifiedBy,#schedulefileidNew
--print 'simple update'
end
end
Now what is my problem:
I am selecting 1 as result in 3rd level which will stored in "#ResultForInsertUpdate" in second level and in 3rd level again..
I am getting 0 in #ResultForInsertUpdate i dont know why, please help me to resolve this prob
Possible this be helpful for you -
1.
CREATE PROCEDURE [dbo].[proc_tblUserScheduleNewUpdateOnly]
(
#Scheduleid BIGINT
, #Contactid UNIQUEIDENTIFIER
, #ScheduleDate DATETIME
, #StartTime VARCHAR(20)
, #EndTime VARCHAR(20)
, #Location BIGINT
, #Area BIGINT
, #Room BIGINT
, #Enddate DATETIME
, #CurrentTime DATETIME
, #ModifiedBy UNIQUEIDENTIFIER
, #schedulefileidNew BIGINT
)
AS BEGIN
UPDATE dbo.tblUserScheduleNew
SET
Contactid = #Contactid
, ScheduleDate = #ScheduleDate
, StartTime = #StartTime
, EndTime = #EndTime
, location = #Location
, Area = #Area
, Room = #Room
, LastModifiedDate = #CurrentTime
, EndDate = #Enddate
, ModifiedBy = #ModifiedBy
, ScheduleFileId = NULLIF(#schedulefileidNew, 0)
WHERE ScheduleID = #Scheduleid
AND IsDeleted = 0
AND isActive = 1
RETURN 1
END
2.
CREATE PROCEDURE [dbo].[proc_tblUserScheduleNewFutureUpdate]
(
#StartDatePassed DATETIME
, #EndDatePassed DATETIME
, #StartTimePassed VARCHAR(20)
, #EndTimePassed VARCHAR(20)
, #CurrentDateTime DATETIME
, #Scheduleid BIGINT
, #Contactid UNIQUEIDENTIFIER
, #Location BIGINT
, #Area BIGINT
, #Room BIGINT
, #ModifiedBy UNIQUEIDENTIFIER
, #schedulefileidNew BIGINT
)
AS BEGIN
IF
CONVERT(DATE, #StartDatePassed, 101) > CONVERT(DATE, #CurrentDateTime, 101)
AND
CONVERT(DATE, #EndDatePassed, 101) > CONVERT(DATE, #CurrentDateTime, 101)
AND
CONVERT(DATE, #EndDatePassed, 101) > CONVERT(DATE, #StartDatePassed, 101)
BEGIN
DECLARE #ResultForInsertUpdate VARCHAR(200)
EXEC #ResultForInsertUpdate = dbo.proc_tblUserScheduleNewUpdateOnly
#Scheduleid
, #Contactid
, #StartDatePassed
, #StartTimePassed
, #EndTimePassed
, #Location
, #Area
, #Room
, #EndDatePassed
, #CurrentDateTime
, #ModifiedBy
, #schedulefileidNew
RETURN #ResultForInsertUpdate
END
ELSE BEGIN
RETURN 2
END
END
3.
CREATE PROCEDURE proc_tblUserScheduleNewUpdateWithAllRoomsOption
(
#StartDatePassed DATETIME,
#EndDatePassed DATETIME,
#StartTimePassed VARCHAR(20),
#EndTimePassed VARCHAR(20),
#CurrentDateTime DATETIME,
#Scheduleid BIGINT,
#Contactid UNIQUEIDENTIFIER,
#Location BIGINT,
#Area BIGINT,
#Room BIGINT,
#ModifiedBy UNIQUEIDENTIFIER,
#schedulefileidNew BIGINT,
#OldStartDate DATETIME,
#OldEndDate DATETIME,
#OldStartTime VARCHAR(20),
#OldEndTime VARCHAR(20),
#OldContactid UNIQUEIDENTIFIER,
#OldLocation BIGINT,
#OldArea BIGINT,
#OldRoom BIGINT
)
AS BEGIN
DECLARE
#row_count INT
, #intFlag INT = 0
, #locationIdForLoop BIGINT
, #AreaIdForLoop BIGINT
, #RoomIdForLoop BIGINT
, #ResultForInsertUpdate INT = 1
CREATE TABLE #tempTable (RowNum INT, LocationId BIGINT, AreaId BIGINT, RoomId BIGINT)
IF #Area = 0 AND #Room = 0 BEGIN
INSERT INTO #tempTable (RowNum, LocationId, AreaId, RoomId)
SELECT
ROW_NUMBER() OVER (ORDER BY LocationId DESC) RowNum
, LocationId
, AreaId
, RoomId
FROM dbo.tblroomnew a
WHERE a.AreaId IN (
SELECT b.AreaId
FROM dbo.tblareanew b
WHERE b.LocationId = #Location
)
SELECT
#row_count = COUNT(1)
, #intFlag = 1
FROM #tempTable
WHILE (#intFlag <= #row_count) BEGIN
SELECT
#locationIdForLoop = LocationId
, #AreaIdForLoop = AreaId
, #RoomIdForLoop = RoomId
FROM #tempTable
WHERE RowNum=#intFlag
IF #ResultForInsertUpdate = 1 BEGIN
IF EXISTS (
SELECT 1
FROM dbo.tbluserschedulenew
WHERE
CONVERT(DATETIME,ScheduleDate,101)=CONVERT(DATETIME,#OldStartDate,101) AND
CONVERT(DATETIME,EndDate,101)=CONVERT(DATETIME,#OldEndDate,101) AND
CONVERT(TIME,StartTime,108)=CONVERT(TIME,#OldStartTime,108) AND
CONVERT(TIME,EndTime,108)=CONVERT(TIME,#OldEndTime,108) AND contactid=#OldContactid
AND location=#OldLocation
AND Area=#OldArea
AND Room=#OldRoom
)
BEGIN
PRINT 'Update First record'
EXEC #ResultForInsertUpdate=proc_tblUserScheduleNewFutureUpdate
#StartDatePassed
, #EndDatePassed
, #StartTimePassed
, #EndTimePassed
, #CurrentDateTime
, #Scheduleid
, #Contactid
, #locationIdForLoop
, #AreaIdForLoop
, #RoomIdForLoop
, #ModifiedBy
, #schedulefileidNew
RETURN #ResultForInsertUpdate
END
ELSE
BEGIN
EXEC proc_tblUserScheduleNewLatestInsert
#Contactid
, #StartDatePassed
, #StartTimePassed
, #EndTimePassed
, #locationIdForLoop
, #AreaIdForLoop
, #RoomIdForLoop
, #EndDatePassed
, #ModifiedBy
, 0
, #CurrentDateTime
END
END
ELSE BEGIN
RETURN #ResultForInsertUpdate
END
SELECT #intFlag = #intFlag + 1
END
END
ELSE
BEGIN
IF #Area != 0 AND #Room = 0 BEGIN
INSERT INTO #tempTable (RowNum, LocationId, AreaId, RoomId)
SELECT
ROW_NUMBER() OVER (ORDER BY LocationId DESC) RowNum
, LocationId
, AreaId
, RoomId
FROM dbo.tblroomnew a
SELECT #row_count = COUNT(1)
FROM #tempTable
END
ELSE BEGIN
EXEC dbo.proc_tblUserScheduleNewFutureUpdate
#StartDatePassed
, #EndDatePassed
, #StartTimePassed
, #EndTimePassed
, #CurrentDateTime
, #Scheduleid
, #Contactid
, #location
, #Area
, #Room
, #ModifiedBy
, #schedulefileidNew
END
END
END

stored procedure with insert & update using identity column

I have a table called 'tasks' in that 'task id' is identity column, for that table I have to write save stored procedure, in which when 'task id' is not given it should insert the values and when 'task id' is given it should update the table.
how can this achievable when task id is identity column could anyone explain with example.
here is the code
Alter PROCEDURE TaskSave
(
#taskid int,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
IF Exists( select null from TblTasks where TaskId=#TaskId)
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
First of all, give your input variable TaskID a default value like below, then simply check to see if the variable is NULL, if so, insert a new row
Alter PROCEDURE TaskSave
(
#taskid int = NULL,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
IF #taskid IS NULL
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
You are close, check if the record doesn't exist and perform insert, otherwise update. You can also declare the #TaskId parameter as OUTPUT and return it when inserting, using the SCOPE_IDENTITY() function:
ALTER PROCEDURE TaskSave(
#TaskId INT = NULL OUTPUT
, #ProjectId INT
, #EmployeeId INT
, #TaskName NVARCHAR(50)
, #Duration_Hrs INT
, #StartDate NVARCHAR(20)
, #FinishDate NVARCHAR(20)
, #CreateUserId INT
, #CreatedDate NVARCHAR(20)
, #ModifiedUserID INT
, #ModifiedDate NVARCHAR(20)
, #Is_CommonTask BIT
)
AS
BEGIN
IF NOT(EXISTS(SELECT * FROM TblTasks WHERE TaskId = #TaskId))
BEGIN
INSERT INTO TblTasks(
ProjectId
, EmployeeId
, TaskName
, Duration_Hrs
, StartDate
, FinishDate
, CreateUserId
, CreatedDate
, ModifiedUserID
, ModifiedDate
, Is_CommonTask
)
VALUES(
#ProjectId
, #EmployeeId
, #TaskName
, #Duration_Hrs
, #StartDate
, #FinishDate
, #CreateUserId
, #CreatedDate
, #ModifiedUserID
, #ModifiedDate
, #Is_CommonTask
)
SET #TaskId = SCOPE_IDENTITY()
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate = #StartDate
, FinishDate = #FinishDate
, Duration_Hrs = #Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
declare #taskid parameter as NULL. the if it is null then insert else update. see below.
Alter PROCEDURE TaskSave
(
#taskid int =NULL,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
if #taskid is null
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#taskid
END
END
GO
In cases like these, I used to create a general stored procedure which is capable of inserting, updating and deleting an item. The general pattern looked like this
create procedure Modify_MyTable
#Action char(1),
#Data int,
#PK int output
as
if #Action = 'I' begin -- Insert
insert into MyTable (Data) values (#Data)
set #PK = Scope_Identity()
end
if #Action = 'M' begin -- Modify
update MyTable set Data = #Data where PKID = #PK
end
if #Action = 'D' begin -- Delete
delete MyTable where PKID = #PK
end
It is quite a while ago when I used this but I found it quite handy as I have all the manipulation code in one SP (I could have used three, of course) and could also add logging features and other basic logic in this procedure.
I am not saying that this is still the best method but it should show the basic logic.

How to pass values from SP to SP?

I have a question, I have a Stored Procedure which returns a value. This Stored Procedure is being executed within another SP and I need to transfer the value into this SP. How can I accomplish this.
Any help will be appreciated.
Thank you
Example:
CREATE PROC [dbo].[isp_CREATE_CONFIG]
#CFG_KEY VARCHAR(15)
, #CFG_SHORTVALUE INT
, #CFG_LONGVALUE VARCHAR(200)
, #CFG_DESC VARCHAR(250)
, #CFG_SHORT_DESC VARCHAR(100)
, #CFG_MISC1 VARCHAR(50)
, #CFG_MISC2 VARCHAR(50)
, #CFG_MISC3 VARCHAR(50)
, #CFG_MISC4 VARCHAR(50)
, #CFG_MISC5 VARCHAR(50)
, #CFG_USER VARCHAR(20)
, #CFG_MSG VARCHAR(250) OUTPUT
AS
DECLARE
#c_ErrMsg VARCHAR(200)
, #c_ErrNum VARCHAR(5)
, #c_Continue INT
, #c_Date VARCHAR(20)
/* Assign value to local variables */
SET #c_Date = GETDATE()
SET #c_Continue = 0
/* Run Validations */
IF EXISTS (SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
SET #c_ErrNum = 60001
SET #c_ErrMsg = 'Configuration Key (' + #CFG_KEY + ') already exist. Please check System Configuration. Error: ' + #c_ErrNum
SET #CFG_MSG = #c_ErrMsg
SET #c_Continue = 1
END
/* Create Configuration */
SET #CFG_MSG = ''
IF #c_Continue = 0
BEGIN
IF NOT EXISTS(SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
INSERT INTO CONFIG
(
cfg_key , cfg_short_value , cfg_long_value , cfg_desc ,cfg_short_desc
, cfg_misc1 , cfg_misc2 , cfg_misc3 , cfg_misc4
, cfg_misc5 , cfg_add_who , cfg_edit_date , cfg_edit_who
)
VALUES
(
#CFG_KEY , #CFG_SHORTVALUE , #CFG_LONGVALUE , #CFG_DESC , #CFG_SHORT_DESC
, #CFG_MISC1 , #CFG_MISC2 , #CFG_MISC3 , #CFG_MISC4
, #CFG_MISC5 , #CFG_USER , #c_Date , #CFG_USER
)
SET #CFG_MSG = 'Configuration has been created.'
END
END
GO
Your stored procedure that returns the value has a parameter declared as OUTPUT, something like this:
CREATE PROCEDURE my_returning_proc (#ret VARCHAR(10) OUTPUT) AS
BEGIN .... END
If you want to use this value you need to call the STORED PROCEDURE like this:
DECLARE #var VARCHAR(10);
EXEC my_returning_proc #var OUTPUT;
PRINT #var
The key's here is to add OUTPUT into EXEC statement
EDIT: Thanks for providing example.
For your case you would call the stored procedure like this:
DECLARE #var_returned VARCHAR(250);
EXEC [dbo].[isp_CREATE_CONFIG] 'BLAH', 0, 'BLAH', 'BLAH', 'BLAH', ......, #var_returned OUTPUT
By return a value, I assume you mean using return. You can also declare output parameters for the stored procedure.
Here is how:
declare #retval int;
exec #retval = <stored procedure call>
Here is a simple code sample anyone can try:
create procedure dum as return 5
declare #retval int;
exec #retval = dum
select #retval
I use this technique all the time to return status from stored procedures.

insert stored procedure, check if row exists

I am using sql server 2005 and want to insert a row into a database table, however i am getting an incorrect syntax at values. and also i want to make sure what i am adding already doesnt exist i think this is right but i have that one syntax error.
create PROCEDURE [dbo].[directway]
#tour as varchar(50),
#tourname as varchar(50),
#taskname as varchar(50) ,
#deptdate as varchar(50),
#tasktype as varchar(50) ,
#desc as varchar(50) ,
#duedate as varchar(50) ,
#agent as varchar(50),
#graceperiod as varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO dashboardtasks
([tour]
,[tourname]
,[taskname]
,[deptdate]
,[tasktype]
,[desc]
,[duedate]
,[agent]
,[graceperiod]
VALUES (#tour,
#tourname,
#taskname ,
#deptdate,
#tasktype ,
#desc ,
#duedate ,
#agent ,
#graceperiod
)
WHERE NOT EXISTS(SELECT *
FROM dashboardtasks
WHERE ( #tour = dashboardtasks.tour
and #taskname = dashboardtasks.taskname
and #deptdate = dashboardtasks.deptdate
and #duedate = dashboardtasks.duedate
and #tourname = dashboardtasks.tourname
and #agent = dashboardtasks.agent
)
)
END
You've just got it a bit the wrong way round
IF NOT EXISTS(SELECT *
FROM dashboardtasks
WHERE ( #tour = dashboardtasks.tour
and #taskname = dashboardtasks.taskname
and #deptdate = dashboardtasks.deptdate
and #duedate = dashboardtasks.duedate
and #tourname = dashboardtasks.tourname
and #agent = dashboardtasks.agent
)
)
BEGIN
INSERT INTO dashboardtasks
([tour]
,[tourname]
,[taskname]
,[deptdate]
,[tasktype]
,[desc]
,[duedate]
,[agent]
,[graceperiod])
VALUES (#tour,
#tourname,
#taskname ,
#deptdate,
#tasktype ,
#desc ,
#duedate ,
#agent ,
#graceperiod
)
END