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

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

Related

SQL Insert Data to Temporary Table and Save the result as a View

I'm trying to do two things with the below query:
edit the query to get all dates that are only between 'd|' and ')()'.....so for example in clndr_data (0||3(d|41429)()) (0||4(d|41464)( (0||0(s|09:00|f|15:00)()))) returns only 41429. The query below returns all dates after '|d'.
Store the output as View (Proj_ID, Clndr_ID, Dates)
DECLARE #project_name varchar(50) = 'NA63-TEN-20-05-12-01'
DECLARE #project_id int = (SELECT [proj_id] FROM [PMDB].[dbo]. [PROJECT] WHERE [proj_short_name] = #project_name)
DECLARE #calendar int = (SELECT [clndr_id] FROM [PMDB].[dbo].[PROJECT] WHERE [proj_short_name] = #project_name)
DECLARE #clndr_id int
DECLARE #walker int = 0
DECLARE #holder varchar(MAX)
DECLARE #date date
DECLARE #temp_tb table([id] int , [value] varchar(50))
SET #holder = (SELECT [clndr_data] FROM [PMDB].[dbo].[CALENDAR] WHERE [clndr_id] = #calendar )
SET #clndr_id = (SELECT [clndr_id] FROM [PMDB].[dbo].[CALENDAR] WHERE [clndr_id] = #calendar)
WHILE CHARINDEX('d|', #holder) > 0
BEGIN
SET #walker = CHARINDEX('d|', #holder) + 2
SET #date = DATEADD(D, CAST((SELECT SUBSTRING(#holder, #walker, 5)) AS int) - 2, '01/01/1900')
INSERT INTO #temp_tb VALUES (#clndr_id, #date)
SET #holder = SUBSTRING(#holder, #walker + 5, LEN(#holder))
END
SELECT * FROM #temp_tb
I joined your PROJECT and CALENDAR tables. Then set the parameters to the corresponding values of proj_id and clndr_id for preparation before INSERT since the value for the date_value column needs to be processed first inside the WHILE.
Connected to the question : SQL While Loop exists
DECLARE #project_name varchar(50) = 'NA63-TEN-20-05-12-01'
DECLARE #project_id int
DECLARE #clndr_id int
DECLARE #walker int = 0
DECLARE #holder varchar(MAX)
DECLARE #date date
DECLARE #data varchar(MAX)
DECLARE #temp_tb table([proj_id] int, [clndr_id] int , [date_value] date)
SELECT #project_id = [p].[proj_id]
,#clndr_id = [p].[clndr_id]
,#holder = [c].[clndr_data]
FROM [PMDB].[dbo].[PROJECT] AS [p]
INNER JOIN [PMDB].[dbo].[CALENDAR] AS [c] ON [p].[clndr_id] = [c].[clndr_id]
WHERE [p].[proj_short_name] = #project_name
WHILE #walker &lt&gt LEN(#holder) + 1
BEGIN
IF SUBSTRING(#holder, #walker, 2) = 'd|'
BEGIN
SET #data = SUBSTRING(#holder, #walker, 10)
IF SUBSTRING(#data, LEN(#data) - 2, 3) = ')()'
BEGIN
SET #date = DATEADD(D, CAST(SUBSTRING(#data, 3, 5) AS int) -2, '01/01/1900')
INSERT INTO #return_tb VALUES (#project_id, #clndr_id, #date)
END
END
SET #walker = #walker + 1
END
SELECT * FROM #temp_tb
If you want to save this as a view, create the code above as function first.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
CREATE FUNCTION GetProjectDates
(
#project_name varchar(50)
)
RETURNS #return_tb TABLE([proj_id] int, [clndr_id] int , [date_value] date)
AS
BEGIN
-- Add the SELECT statement with parameter references here
DECLARE #project_id int
DECLARE #clndr_id int
DECLARE #walker int = 0
DECLARE #holder varchar(MAX)
DECLARE #date date
DECLARE #data varchar(MAX)
SELECT #project_id = [p].[proj_id]
,#clndr_id = [p].[clndr_id]
,#holder = [c].[clndr_data]
FROM [PMDB].[dbo].[PROJECT] AS [p]
INNER JOIN [PMDB].[dbo].[CALENDAR] AS [c] ON [p].[clndr_id] = [c].[clndr_id]
WHERE [p].[proj_short_name] = #project_name
WHILE #walker &lt&gt LEN(#holder) + 1
BEGIN
IF SUBSTRING(#holder, #walker, 2) = 'd|'
BEGIN
SET #data = SUBSTRING(#holder, #walker, 10)
IF SUBSTRING(#data, LEN(#data) - 2, 3) = ')()'
BEGIN
SET #date = DATEADD(D, CAST(SUBSTRING(#data, 3, 5) AS int) -2, '01/01/1900')
INSERT INTO #return_tb VALUES (#project_id, #clndr_id, #date)
END
END
SET #walker = #walker + 1
END
RETURN
END
GO
Then save the code below as your view:
SELECT * FROM [GetProjectDates]('NA63-TEN-20-05-12-01')
I am not sure but might be below query will help you. As I assumed like date value in 5 digit only.
create table #yourtable (
cola varchar(1000)
)
;
insert into #yourtable
values ('(0||3(d|41429)())')
insert into #yourtable
values ('(0||4(d|41464)( (0||0(s|09:00|f|15:00)())))')
select SUBSTRING(cola,9,5)
from #yourtable
where PATINDEX('%[0-9][0-9][0-9][0-9][0-9])()%', cola )>0

Create a stored procedure to insert new data into a table

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

Invalid object name 'table1'

DECLARE
#empid INT
, #schedindate DATETIME
, #ss NVARCHAR(100)
, #indice NVARCHAR(3)
, #FromDate DATETIME
, #ToDate DATETIME
, #TimeInR NVARCHAR(20)
, #TimeOutR DATETIME,#day nvarchar(3)
SELECT
#FromDate = '20090114'
, #ToDate = '20100130'
DECLARE #temp TABLE
(
schedindate DATETIME
, TimeInR VARCHAR(10)
, TimeOutR VARCHAR(10)
, empid INT
)
delete from PayrollTEST.dbo.[table1]
INSERT INTO #temp (schedindate, TimeInR, TimeOutR, empid)
SELECT DISTINCT
schedindate
, TimeInR
, TimeOutR
, empid
FROM dbo.ta_timecard
WHERE schedindate BETWEEN #FromDate AND #ToDate
DECLARE #ids TABLE(id BIGINT IDENTITY(1,1), emp BIGINT)
INSERT INTO #ids (emp)
SELECT DISTINCT empid
FROM #temp
INSERT INTO PayrollTEST.dbo.[table1](id, EmpID)
SELECT id, emp
FROM #ids
DECLARE cc CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT DISTINCT empid
FROM #temp
OPEN cc
FETCH NEXT FROM cc INTO #empid
WHILE (##fetch_status = 0) BEGIN
SELECT
#indice = (select DATEDIFF(day,#fromdate, t.SchedInDate))
--, #TimeInR = t.TimeInR
, #schedindate = t.SchedInDate
, #day = dbo.ta_dayofweek(#schedindate)
FROM #temp t
WHERE empid = #empid
print(#indice)
print(#day)
print(#schedindate)
print(#TimeInR)
-- SELECT #ss = 'update table1 set nod' + #indice
-- + ' = '+ convert(nvarchar(3),#day) +' , din'
-- + #indice + ' = ' + #Schedindate + ' where empid = ' + CAST(#empid AS NVARCHAR(20))
SELECT #ss = 'update table1 set nod' + #indice
+ ' = '+ convert(nvarchar(3),#day) + ' where empid = ' + CAST(#empid AS NVARCHAR(20))
EXEC master.dbo.sp_executesql #ss
FETCH NEXT FROM cc INTO #empid
END
CLOSE cc
DEALLOCATE cc
Why am I getting this error? i'm in the right database and the table exist. I appreciate any help
Did you make sure that you are in the right database ?
you can run SELECT DB_NAME() to see your current databse

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.

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