T-SQL 2008- Exit when Value is NULL - sql-server

I am looking for a way to exit an T-SQL script when #Value is null. This is what I have so far but it does not work as expected:
SELECT
#Value,
CASE
WHEN #Value IS NULL
RAISERROR('EXIT', 16, 1)
FROM
table
WHERE
name LIKE 'test'

Perhaps this will work for you:
DECLARE #Value INT = 1
IF( #Value IS NULL)
BEGIN
RAISERROR('Exit',16,1)
END
ELSE
BEGIN
SELECT #Value
END

IF #Value IS NULL RAISERROR('EXIT', 16,1);

Using a cursor and a temp table you can get the output you want. don't know if that's the goal,
USE AdventureWorksLT2012
DECLARE #CustomerID AS INT
DECLARE #CompanyName AS VARCHAR(MAX)
DECLARE #EmailAddress AS VARCHAR(MAX)
CREATE TABLE #output (CustomerID INT,CompanyName VARCHAR(MAX),EmailAddress VARCHAR(MAX))
DECLARE testCursor CURSOR
FOR
SELECT TOP (100)
CustomerID
,CompanyName
,EmailAddress
FROM SalesLT.Customer
ORDER BY customerID DESC;
OPEN testCursor;
FETCH NEXT FROM testCursor
INTO #CustomerID, #CompanyName, #emailAddress;
if #EmailAddress is not null
BEGIN
INSERT INTO #output values( #CustomerID, #CompanyName, #emailAddress);
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM testCursor
INTO #CustomerID, #CompanyName, #emailAddress;
if #EmailAddress is null
BEGIN
RAISERROR('Exit',16,1);
BREAK;
end
INSERT INTO #output values( #CustomerID, #CompanyName, #emailAddress);
END;
END
CLOSE testCursor;
DEALLOCATE testCursor;
SELECT * FROM #output;
DROP TABLE #output

Related

While executing the stored procedure from backend(MSSQL 2012).Unable to open a few modules from pb12.5 desktop application

We have an stored procedure to transfer the data(contract data) from database 1 to database 2(interfacing with SAP to Intermeidate Database , then our database), and this contain loops and more that one table in the execution.And we have an PB12.5 desktop application with several modules like procurement,crewing, employee etc.The issue is here while executing the stored procedure from MSSQL using exec, it will take nearly 2 minutes depend on the recieved data from SAP.During the execution I'm unable to open procurement window and it is opening once the stored procedure completed the execution.The other side employee window is opening without any issue.The below are my findings/comments
Procurement module is using table1 and table2 , but in the stored procedure we are not using any of this tables.We are using table 3 and table 4(but later we will use the table from procurement module in proc)
2.While executing the proc Im able to select the tables from procurement module using select * from table1.
3.None of the table is locking from proc.
4.We have tried the same scenarios from different PC same issue exist.
5.Later we will extend the stored procedure with more tables and multiple loops(cursor)
Below are the small part of procedure(we have to extend more and it is hold now because of this issue)
Many thanks in advance.
alter PROC [spectwosuite].[CST_GENERATE_IPurchase_contract]
as begin
SET NOCOUNT ON;
/**/
--truncate table spectwosuite.CUSTOM_SAP_CONTRACT_ITEM;
--truncate table spectwosuite.CUSTOM_SAP_CONTRACT_header;
--truncate table spectwosuite.CUSTOM_SAP_PROC_LOG;
--Variable declaration
DECLARE #MATERIALNO VARCHAR(20);
DECLARE #PURCHASEDOCNO VARCHAR(20);
DECLARE #PORTID NUMERIC(15);
DECLARE #PRICE DECIMAL(11,2);
DECLARE #PKID NUMERIC(16);
DECLARE #STOCKTYPEID NUMERIC(15);
DECLARE #STOCKTYPECODE VARCHAR(50);
DECLARE #STNAME VARCHAR(50);
DECLARE #UNITID NUMERIC(15);
DECLARE #BUSFLOWID NUMERIC(15);
DECLARE #BUSSTATUSID NUMERIC(15);
DECLARE #ITEMNO VARCHAR(5);
DECLARE #SUBITEMNO VARCHAR(10);
DECLARE #STOCKDISID NUMERIC(15);
DECLARE #PURCONTRACTID NUMERIC(15);
DECLARE #REVISIONNO NUMERIC(15);
DECLARE #DESCR NVARCHAR(100);
DECLARE #ADDRESSID NUMERIC(15);
DECLARE #DELTERMSID NUMERIC(15);
DECLARE #PAYTERMSID NUMERIC(15);
DECLARE #VALIDSTART DATETIME;
DECLARE #VALIDEND DATETIME;
DECLARE #CURRENCY NCHAR(3);
DECLARE #PRODUCTGROUPID NUMERIC(15);
DECLARE #PURCONTRACTPRODUCTGROUPID NUMERIC(15);
DECLARE #MATERIALGRP NVARCHAR(20);
DECLARE #NETPRICE NUMERIC(16,6);
DECLARE #BASEPRICE NUMERIC(16,6);
DECLARE #PRODUCTGROUPLINEID NUMERIC(15);
DECLARE #SECTION VARCHAR(20);
DECLARE #PUREXIST NUMERIC(1);
DECLARE #HEADERPKID NUMERIC(16);
DECLARE #ITEMPRICE NUMERIC(16,6);
DECLARE #BASEITEMPRICE NUMERIC(16,2);
DECLARE #PURCONTRACTVARIABLEID NUMERIC(15);
DECLARE #FACTORVALUE NUMERIC(9,4);
DECLARE #ITEMPERCENTAGE NUMERIC(15,2);
DECLARE #ITEMPRICEDIFF1 NUMERIC(15,2);
DECLARE #ITEMPRICEDIFF2 NUMERIC(15,2);
DECLARE #ITEMPKID NUMERIC(16);
/*CONT1: Transfering all the portid and purchase document number to different table */
--PRINT 'CONT1 START'
--PRINT GETDATE();
BEGIN TRY
--BEGIN TRANSACTION
--BEGIN
SET #SECTION='CONT1';
BEGIN TRANSACTION CONT1
INSERT INTO SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_PORT
(PORTID
,PURCHASE_DOC_NO
)
SELECT DISTINCT PORTID,PURCHASE_DOC_NO FROM SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) WHERE IMPORT_STATUS IS NULL and DELETION_IND NOT IN('L','1')
and portid>0 and MATERIAL_NO<>'' and FACTOR>0 and
not exists (select PORTID from SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_PORT where PORTID=SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_PORT.PORTID
and PURCHASE_DOC_NO =SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_PORT.PURCHASE_DOC_NO) ORDER BY PURCHASE_DOC_NO,PORTID ASC;
COMMIT TRANSACTION CONT1
--END
----INSERT INTO spectwosuite.CUSTOM_SAP_PROC_LOG
---- (STATUS
---- ,DESCRIPTION
---- ,PROCESSEDDATE
---- ,RECORDCOUNT)
---- VALUES
---- (1,
---- 'CONT1'
---- ,GETDATE()
---- ,##ROWCOUNT
---- );
--PRINT 'CONT1 END'
--PRINT GETDATE();
/* CONT1 END */
/*CONT2 Inserting new item which one dont have price in all ports*/
/*Variable declaration*/
--PRINT 'CONT2 START'
--PRINT GETDATE();
-- BEGIN
SET #SECTION='CONT2';
--SELECT DISTINCT CAST(MATERIAL_NO AS VARCHAR(20))AS MATERIAL_NO,PURCHASE_DOC_NO FROM SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) WHERE PURCHASE_DOC_NO='4600000820' and IMPORT_STATUS IS NULL and MATERIAL_NO<>'' and DELETION_IND NOT IN('L','1') and len(material_no)>0 and factor>0 and portid>0 ORDER BY MATERIAL_NO,PURCHASE_DOC_NO ASC;
DECLARE CONT2CR CURSOR FOR
SELECT DISTINCT CAST(MATERIAL_NO AS VARCHAR(20))AS MATERIAL_NO,PURCHASE_DOC_NO FROM SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) WHERE IMPORT_STATUS IS NULL and MATERIAL_NO<>'' and DELETION_IND NOT IN('L','1') and len(material_no)>0 and factor>0 and portid>0 ORDER BY MATERIAL_NO,PURCHASE_DOC_NO ASC;
OPEN CONT2CR
FETCH NEXT FROM CONT2CR INTO #MATERIALNO,#PURCHASEDOCNO
WHILE ##FETCH_STATUS=0
BEGIN
BEGIN TRAN CONT2
select #PKID=MIN(pk_id),#PRICE=MIN(NET_PRICE) from SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) WHERE MATERIAL_NO=#MATERIALNO AND PURCHASE_DOC_NO=#PURCHASEDOCNO and IMPORT_STATUS IS NULL and DELETION_IND NOT IN('L','1') and factor>0 and portid>0;
/*Retreiving port details table*/
DECLARE CONT2PORTCR CURSOR FOR
SELECT DISTINCT portid FROM SAP_INTERFACE.spectwosuite.custom_sap_contract_port WITH(NOLOCK) WHERE (SAP_INTERFACE.spectwosuite.custom_sap_contract_port.purchase_doc_no = #PURCHASEDOCNO) and ( custom_sap_contract_port.portid > 0 ) ;
OPEN CONT2PORTCR
FETCH NEXT FROM CONT2PORTCR INTO #PORTID
WHILE #PORTID>0
BEGIN
IF #PORTID>0
BEGIN
BEGIN TRAN
/*Insert Script*/
SET #SECTION='ITEM_ADDITION';
IF (select COUNT(*) from SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) where MATERIAL_NO=CAST(#MATERIALNO AS varchar(20)) AND PORTID=#PORTID and PURCHASE_DOC_NO=#PURCHASEDOCNO and IMPORT_STATUS IS NULL and DELETION_IND NOT IN('L','1') and factor>0 and portid>0)<=0
BEGIN
INSERT INTO SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM
(DELETION_IND,PURCHASE_DOC_NO,ITEM_NO,MATERIAL_NO,SHORT_TEXT,MATERIAL_GRP,QTY,UOM,NET_PRICE,PORTID,TEMPPORTID,FACTOR)
select DELETION_IND,PURCHASE_DOC_NO,ITEM_NO,MATERIAL_NO,SHORT_TEXT,MATERIAL_GRP,QTY,UOM,NET_PRICE,#PORTID,1252,FACTOR from SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK) WHERE pk_id=#PKID and DELETION_IND<>'1' and IMPORT_STATUS IS NULL;
END
SET #PORTID=0;
COMMIT TRAN
END
FETCH NEXT FROM CONT2PORTCR INTO #PORTID
END
CLOSE CONT2PORTCR
DEALLOCATE CONT2PORTCR
COMMIT TRAN CONT2
FETCH NEXT FROM CONT2CR INTO #MATERIALNO,#PURCHASEDOCNO
END
CLOSE CONT2CR
DEALLOCATE CONT2CR
--END
--INSERT INTO spectwosuite.CUSTOM_SAP_PROC_LOG
-- (STATUS
-- ,DESCRIPTION
-- ,PROCESSEDDATE
-- ,RECORDCOUNT)
-- VALUES
-- (1,
-- 'CONT2'
-- ,GETDATE()
-- ,##ROWCOUNT
-- );
--PRINT 'CONT2 END'
--PRINT GETDATE();
/*CONT2 END*/
/*CONT3*/
--PRINT 'CONT3 START'
--PRINT GETDATE();
SET #SECTION='CONT3';
BEGIN TRAN CONT3
INSERT INTO spectwosuite.CUSTOM_SAP_CONTRACT_HEADER
(TABLEPKID
,PURCHASE_DOC_NO
,COMPANY_CODE
,CREATED_ON_DATE
,VENDOR_CODE
,PAYMENT_TERMS
,PURCHASE_GRP
,VALIDITY_START
,VALIDITY_END
,YOUR_REFERENCE
,OUR_REFERNCE
,TARGET_AMOUNT
,CURRENCY
,DESCRIPTION
,SHIPCODE
,STATUS
,CREATEDATE
,VALIDATESTART
,VALIDATEEND
,INTERNAL_STATUS
,INTERNAL_MESSAGE
)
SELECT
PK_ID
,PURCHASE_DOC_NO
,COMPANY_CODE
,CREATED_ON_DATE
,VENDOR_CODE
,PAYMENT_TERMS
,PURCHASE_GRP
,VALIDITY_START
,VALIDITY_END
,YOUR_REFERENCE
,OUR_REFERNCE
,TARGET_AMOUNT
,CURRENCY
,DESCRIPTION
,SHIPCODE
,STATUS
,CREATEDATE
,VALIDATESTART
,VALIDATEEND
,INTERNAL_STATUS
,INTERNAL_MESSAGE
FROM SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_HEADER WITH(NOLOCK)
where import_status is null and purchase_doc_no<>'' and validity_start<>'' and validity_end<>'' and currency<>''and status>0
and not exists(select pk_id from spectwosuite.CUSTOM_SAP_CONTRACT_HEADER WHERE TABLEPKID= SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_HEADER.PK_ID)
COMMIT TRAN CONT3
--INSERT INTO spectwosuite.CUSTOM_SAP_PROC_LOG
-- (STATUS
-- ,DESCRIPTION
-- ,PROCESSEDDATE
-- ,RECORDCOUNT)
-- VALUES
-- (1,
-- 'CONT3'
-- ,GETDATE()
-- ,##ROWCOUNT
-- );
--PRINT 'CONT3 END'
--PRINT GETDATE();
/*CONT3 END*/
/*CONT4*/
--PRINT 'CONT4 START'
--PRINT GETDATE();
SET #SECTION='CONT4';
BEGIN TRAN CONT4
INSERT INTO spectwosuite.CUSTOM_SAP_CONTRACT_ITEM
(TABLEPKID,PURCHASE_DOC_NO
,ITEM_NO
,DELETION_IND
,MATERIAL_NO
,SHORT_TEXT
,MATERIAL_GRP
,QTY
,UOM
,NET_PRICE
,PORTID
,STOCKTYPEID
,INTERNAL_MESSAGE
,INTERNAL_STATUS
,CONTRACTTYPE
,AGREEMENTSUBITEMNO
,FACTOR
)
select PK_ID,PURCHASE_DOC_NO
,ITEM_NO
,DELETION_IND
,MATERIAL_NO
,SHORT_TEXT
,MATERIAL_GRP
,QTY
,UOM
,NET_PRICE
,PORTID
,STOCKTYPEID
,INTERNAL_MESSAGE
,INTERNAL_STATUS
,CONTRACTTYPE
,AGREEMENTSUBITEMNO
,FACTOR
from SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM WITH(NOLOCK)
where IMPORT_STATUS is null and MATERIAL_NO<>'' and DELETION_IND<>'L' AND PORTID>0 and FACTOR>0 and LEN(SHORT_TEXT)>0 AND LEN(PURCHASE_DOC_NO)>0 AND
not exists (select PK_ID from spectwosuite.CUSTOM_SAP_CONTRACT_ITEM where TABLEPKID= SAP_INTERFACE.spectwosuite.CUSTOM_SAP_CONTRACT_ITEM.PK_ID ) ORDER BY PK_ID ASC;
COMMIT TRAN CONT4
-- /*Inserting History*/
-- /*Transfering process status to interface table.*/
TRUNCATE TABLE spectwosuite.CUSTOM_SAP_CONTRACT_HEADER;
TRUNCATE TABLE spectwosuite.CUSTOM_SAP_CONTRACT_ITEM;
DELETE FROM spectwosuite.CUSTOM_SAP_PROC_LOG WHERE STATUS=99;
COMMIT
-- /*PURCHASE CONTRACT CREATION END*/
-- SET NOCOUNT OFF;
-- --COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE #ERRORNUMBER VARCHAR(20);
DECLARE #ERRMSG VARCHAR(MAX);
SET #ERRORNUMBER=CAST(ERROR_LINE() AS VARCHAR(20));
SET #ERRMSG=ERROR_MESSAGE();
BEGIN TRAN ER
INSERT INTO spectwosuite.CUSTOM_SAP_PROC_LOG
(STATUS
,DESCRIPTION
,PROCESSEDDATE
,RECORDCOUNT
,ERRORMSG)
VALUES
(
88,
#SECTION
,getdate()
,1
,#ERRORNUMBER +','+ #ERRMSG
);
COMMIT TRAN ER
END CATCH
END
Try to add Begin tran and commit Tran without success

SQL Server procedure error - duplicate entries inserted into the table

I am writing a procedure in SQL Server to insert or update records.
The update part of the code is working fine but when I am executing it for inserting, duplicate entries are inserted into the table.
I created the primary key to avoid this error but after creating that I am not able to insert any single record.
Here is the code :
Alter Procedure test_case
#id int,
#name nvarchar(20)
AS
If exists (Select t_id from testing2 where t_id = #id)
begin
update testing2
set t_id = #id, t_name = #name
where t_id = #id
end
else
begin
insert into testing2 (t_id, t_name, last_date, hard)
select
#id, #name, convert(date, getdate()), 'null'
from test
end
On executing it is showing 2 rows affected
You do not require test table in the select query
insert into testing2 (t_id, t_name, last_date, hard)
select
#id as t_id, #name as t_name, convert(date, getdate()) as last_date, 'null' as hard
is enough
I like to break functionality into smaller parts because it helps me to manage code better.
Maybe this is not a good example since it is pretty simple but I will write it anyway.
Create Procedure Testing2_InsertData (
#id int,
#name nvarchar(20)
) As
Set NoCount On
Insert Into testing2
(t_id, t_name, last_date, hard)
Values
( #id, #name, GetDate(), null )
Go
Create Procedure Testing2_UpdateData (
#id int,
#name nvarchar(20)
) As
Set NoCount On
Update testing2 Set
t_name = #name --, maybe last_date = GetDate()
Where ( t_id = #id )
Go
Create Procedure Testing2_SaveData (
#id int,
#name nvarchar(20)
) As
Set NoCount On
If ( Exists( Select t_id From testing2 Where ( t_id = #id ) ) )
Exec Testing2_UpdateData #id, #name
Else
Exec Testing2_InsertData #id, #name
Go

SQL Server: Nested cursor syntax error

I tried to define following SQL Server nested cursor statement: I loop calendars and migrate them from cut_calendar to sd_calendar. Each calendar also have calendar days. They are also moved by each calendar move.
DECLARE #id NUMERIC(20)
DECLARE #sdCalendarId NUMERIC(20)
DECLARE #calendarTypId NUMERIC(5)
DECLARE #name NVARCHAR(35)
DECLARE #description NVARCHAR(255)
DECLARE #ptyId NUMERIC(20)
DECLARE #lockCode NVARCHAR(20)
DECLARE #dataOwnerId NUMERIC(20)
DECLARE #cntId NUMERIC(20)
DECLARE #nonBusinessDaysMonday CHAR(1)
DECLARE #nonBusinessDaysTuesday CHAR(1)
DECLARE #nonBusinessDaysWednesday CHAR(1)
DECLARE #nonBusinessDaysThursday CHAR(1)
DECLARE #nonBusinessDaysFriday CHAR(1)
DECLARE #nonBusinessDaysSaturday CHAR(1)
DECLARE #nonBusinessDaysSunday CHAR(1)
DECLARE #ccyId NUMERIC(20)
DECLARE #code NVARCHAR(30)
DECLARE #version NUMERIC(10)
DECLARE #seal VARCHAR(255)
DECLARE #lstUpdTs DATETIME
DECLARE #day_id NUMERIC(20)
DECLARE #day_calDate DATETIME
DECLARE #day_lockCode NVARCHAR(20)
DECLARE #day_calComment NVARCHAR(255)
DECLARE #day_dataOwnerId NUMERIC(20)
DECLARE #day_calendarId NUMERIC(20)
DECLARE #day_calRecurring CHAR(1)
DECLARE #day_version NUMERIC(10)
DECLARE #day_seal VARCHAR(255)
DECLARE #day_lstUpdTs DATETIME
DECLARE #day_sdCalendarDaysId NUMERIC(20)
DECLARE #sdCodeId NUMERIC(20)
DECLARE cursorCutoffCalendar CURSOR FOR
SELECT ID, NAME, CALENDAR_TYP_ID,DESCRIPTION,PTY_ID,LOCK_CODE,DATA_OWNER_ID,CNT_ID,NON_BUSINESS_DAYS_MONDAY,NON_BUSINESS_DAYS_TUESDAY,NON_BUSINESS_DAYS_WEDNESDAY,NON_BUSINESS_DAYS_THURSDAY,NON_BUSINESS_DAYS_FRIDAY,NON_BUSINESS_DAYS_SATURDAY,NON_BUSINESS_DAYS_SUNDAY,CCY_ID,CODE,VERSION,SEAL,LST_UPD_TS
FROM CUT_CALENDAR
WHERE ID != 1
OPEN cursorCutoffCalendar
FETCH NEXT FROM cursorCutoffCalendar INTO #id, #name, #calendarTypId, #description, #ptyId, #lockCode, #dataOwnerId, #cntId, #nonBusinessDaysMonday, #nonBusinessDaysTuesday, #nonBusinessDaysWednesday, #nonBusinessDaysThursday, #nonBusinessDaysFriday, #nonBusinessDaysSaturday, #nonBusinessDaysSunday, #ccyId, #code, #version, #seal, #lstUpdTs
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #sdCalendarId = COALESCE(MAX(ID),1) FROM SD_CALENDAR
SET #sdCalendarId = #sdCalendarId + 1
UPDATE CUT_CALENDAR_DAY
SET CALENDAR_ID = #sdCalendarId
WHERE CALENDAR_ID = #id
SELECT #sdCodeId = ID FROM SD_CALENDAR WHERE CODE = #code
IF #sdCodeId > 0
SET #code = CONCAT(#code, '_co')
ELSE
INSERT INTO SD_CALENDAR (ID, NAME, CALENDAR_ROLE_ID,DESCRIPTION,USE_IN_CUTOFF,PTY_ID,LOCK_CODE,DATA_OWNER_ID,CNT_ID,NON_BUSINESS_DAYS_MONDAY,NON_BUSINESS_DAYS_TUESDAY,NON_BUSINESS_DAYS_WEDNESDAY,NON_BUSINESS_DAYS_THURSDAY,NON_BUSINESS_DAYS_FRIDAY,NON_BUSINESS_DAYS_SATURDAY,NON_BUSINESS_DAYS_SUNDAY,CCY_ID,CODE,VERSION,SEAL,LST_UPD_TS)
VALUES(#sdCalendarId, #name, #calendarTypId,#description,1,#ptyId,#lockCode,#dataOwnerId,#cntId,#nonBusinessDaysMonday,#nonBusinessDaysTuesday,#nonBusinessDaysWednesday,#nonBusinessDaysThursday,#nonBusinessDaysFriday,#nonBusinessDaysSaturday,#nonBusinessDaysSunday,#ccyId,#code,#version,#seal,#lstUpdTs)
DECLARE cursorCutoffCalendarDays CURSOR FOR
SELECT ID, CAL_DATE, LOCK_CODE,CAL_COMMENT,DATA_OWNER_ID,CALENDAR_ID,CAL_RECURRING,VERSION,SEAL,LST_UPD_TS
FROM CUT_CALENDAR_DAY
WHERE ID != 1
OPEN cursorCutoffCalendarDays
FETCH NEXT FROM cursorCutoffCalendarDays INTO #day_id, #day_calDate, #day_lockCode, #day_calComment, #day_dataOwnerId, #day_calendarId, #day_calRecurring, #day_version, #day_seal, #day_lstUpdTs
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #day_sdCalendarDaysId = COALESCE(MAX(ID),1) FROM SD_CALENDAR_DAY
SET #day_sdCalendarDaysId = #day_sdCalendarDaysId + 1
INSERT INTO SD_CALENDAR_DAY (ID, CAL_DATE, LOCK_CODE,CAL_COMMENT,DATA_OWNER_ID,CALENDAR_ID,CAL_RECURRING,VERSION,SEAL,LST_UPD_TS)
VALUES(#day_sdCalendarDaysId, #day_calDate, #day_lockCode, #day_calComment, #day_dataOwnerId, #day_calendarId, #day_calRecurring, #day_version, #day_seal, #day_lstUpdTs)
FETCH NEXT FROM cursorCutoffCalendarDays INTO #day_sdCalendarDaysId, #day_calDate, #day_lockCode, #day_calComment, #day_dataOwnerId, #day_calendarId, #day_calRecurring, #day_version, #day_seal, #day_lstUpdTs
END
CLOSE cursorCutoffCalendarDays
DEALLOCATE cursorCutoffCalendarDays
GO
DELETE FROM CUT_CALENDAR
WHERE ID = #id
FETCH NEXT FROM cursorCutoffCalendar INTO #sdCalendarId, #name, #calendarTypId, #description, #ptyId, #lockCode, #dataOwnerId, #cntId, #nonBusinessDaysMonday, #nonBusinessDaysTuesday, #nonBusinessDaysWednesday, #nonBusinessDaysThursday, #nonBusinessDaysFriday, #nonBusinessDaysSaturday, #nonBusinessDaysSunday, #ccyId, #code, #version, #seal, #lstUpdTs
END
CLOSE cursorCutoffCalendar
DEALLOCATE cursorCutoffCalendar
GO
Now when I run this, I get following error:
SQLServerException: Incorrect syntax near 'cursorCutoffCalendarDays'.
cursorCutoffCalendarDays is the inner cursor of my statement.
Try removing GO from:
CLOSE cursorCutoffCalendarDays
DEALLOCATE cursorCutoffCalendarDays
GO
And I agree with the comment you got from GarethD, I used to write cursors like this but then I asked how to do it without the cursor and got a nice explanation
Blockquote
Remove Go from this line then try
CLOSE cursorCutoffCalendarDays
DEALLOCATE cursorCutoffCalendarDays

insert collection of data into sql server columns with storedprocedure

i'm begginer in sql server
i want to insert collection of data into the column in stored procedure
i want pass data from c# like this (100,'3,5,4,2,9') and insert to the column like this
ID Number
100 3
100 5
100 4
100 2
100 9
My procedure code
ALTER PROCEDURE [dbo].[Number]
#Number CHAR(10),
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl
VALUES(#Number)
SELECT 1
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
how i can do it?
thank you
Procedure Definition
ALTER PROCEDURE [dbo].[Number]
#Value INT,
#Number Varchar(100),
#Sucecc BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #xml xml;
BEGIN TRY
SET #xml = cast(('<X>'+replace(#Number,',' ,'</X><X>')+'</X>') as xml)
INSERT INTO NumbersTbl (Column1 , Column2)
SELECT #Value, N.value('.', 'varchar(100)') as value
FROM #xml.nodes('X') as T(N)
SET #Sucecc = 1;
END TRY
BEGIN CATCH
EXEC SQLError
SET #Sucecc = 0;
END CATCH
END
Call Procedure
DECLARE #Result BIT;
Exec [dbo].[Number] #Value = 100
,#Number = '3,5,4,2,9'
,#Sucecc = #Result OUTPUT
First you can create the special function to parse input numbers:
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Numbers] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
And then edit your procedure:
ALTER PROCEDURE [dbo].[Number]
#ID INT,
#Number VARCHAR(MAX)
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl(ID, Number)
SELECT #ID, Numbers
FROM dbo.splitstring(#Number)
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
Call: EXEC Number 100,'3,5,4,2,9'

How i can use cursor to delete record from table

I want to use cursor to delete record from table. How can I do it?
I use MSSQL 2008 Express this code does not delete anything from #temp. I also tried where current of cursor_name did not work.
Here is my sample code:
use AdventureWorks
drop table #temp
select * into #temp from HumanResources.Employee;
declare #eid as int;
declare #nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;
WHILE ##FETCH_STATUS = 0
BEGIN
IF (#eid > 10)
BEGIN
delete from #temp where #temp.EmployeeID = #eid;
END
FETCH NEXT FROM Employee_Cursor;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO
select * from #temp
thanks in advance
use AdventureWorks
select * into #temp from HumanResources.Employee;
declare #eid as int;
declare #nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;
WHILE ##FETCH_STATUS = 0
BEGIN
IF (#eid > 10)
BEGIN
delete from #temp where current of Employee_Cursor
END
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
select * from #temp
drop table #temp
this works for me
There is a much simpler answer - use this command:
delete from HumanResources.Employee where current of Employee_Cursor
It's called 'Positioned delete' and described at MSDN.
Could you please try in below ways, thanks for your time.
You have fetched data from cursor but didn't push into your variables missed in WHILE loop, please have a look on below code, thanks.
drop table #temp
select * into #temp from Employee;
declare #eid as int;
declare #nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;
WHILE ##FETCH_STATUS = 0
BEGIN
IF (#eid > 10)
BEGIN
delete from #temp where #temp.EmployeeID = #eid;
END
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO
select * from #temp
Update:
I've changes in 2nd FETCH statement, just have added below highlighted part, thanks
FETCH NEXT FROM Employee_Cursor INTO #eid , #nid ;

Resources