Unable to exit Sql cursor - sql

This is hard for me to explain but I have tried my best to make it as easy for you all as I can.
I have two tables. One stores information about customer tbl_installations. Another his internet bills tbl_bills (this one is more important).
tbl_installations
CREATE TABLE [dbo].[tbl_installations](
[SrNo] [int] IDENTITY(1000,1) NOT NULL,
[name] [varchar](200) NULL,
[email] [varchar](100) NULL,
[phone] [varchar](20) NULL,
[plandesc] [varchar](50) NULL,
[plancost] [money] NULL,
[amtpaid] [money] NULL,
[amtbalance] [money] NULL,
[address] [varchar](500) NULL,
[referencename] [varchar](20) NULL,
[installationdate] [date] NULL,
[planduration] [int] NULL,
[MkrId] [varchar](20) NULL,
[MkrDt] [datetime] NULL,
[FromDate] [datetime] NULL,
[ToDate] [datetime] NULL,
[ExpiryDate] [datetime] NULL,
[Status] [varchar](20) NULL,
[CustomerId] [varchar](20) NULL,
[ServiceTax] [money] NULL,
[TotalAmt] [money] NULL
) ON [PRIMARY]
tbl_bills
CREATE TABLE [dbo].[tbl_Bills](
[Srno] [int] IDENTITY(1,1) NOT NULL,
[CustomerId] [varchar](20) NULL,
[PlanDuration] [int] NULL,
[Amount] [money] NULL,
[PaidAmt] [money] NULL,
[discount] [money] NULL,
[PlanDesc] [varchar](20) NULL,
[FromDate] [datetime] NULL,
[ToDate] [datetime] NULL,
[MkrId] [varchar](20) NULL,
[MkrDt] [datetime] NULL,
[ServiceTax] [money] NULL,
[TotalAmt] [money] NULL,
[PendingAmt] AS ([TotalAmt]-([PaidAmt]+[discount])),
[PaidStatus] [varchar](10) NULL
) ON [PRIMARY]
THIS SCRIPT WILL GIVE YOU DATA THAT I HAVE:
insert into tbl_installations(name,email,phone,plandesc,plancost,amtpaid,amtbalance,address,referencename,installationdate,planduration,MkrId,
MkrDt,FromDate,ToDate,ExpiryDate,Status,CustomerId,ServiceTax,TotalAmt)
values('Gulzar','asdasd','3242342',null,null,null,null,'asda asd aada','ref name',GETDATE()-4,1,'arbaaz', GETDATE(),null,null,
null,'INSTALLED','C2002',null,null )
insert into tbl_bills (PlanDuration,Amount,PaidAmt,discount,PlanDesc,FromDate,ToDate,PaidStatus,MkrId,MkrDt,ServiceTax,TotalAmt,CustomerId)
values(1,800,600,0,'1MB',GETDATE()-4,DATEADD(month,1, GETDATE()-4),'PAID','Arbaaz',getdate(),800*(12.36/100),800+800*(12.36/100),'C2001')
PendingAmt in tbl_bills is a computer column which calculates the pending amount based on totalamt - (paidamt+discount)
tbl_bills.Amount is the subsription cost eg: 800
tbl_bills.TotalAmt is sum of Amount+ServiceTax
Scenario
First Month:
Customer's subsription cost(Amount) is 800
PaidAmt=600
ServiceTax=98.88
TotalAmt=898.88
PendingAmt=298.88(computed field)
Second Month:
Customer still has same subscription worth 800 (total 898.88)
But he pays 1100 so that he settles some of pending amount.
This 1100 must first settle all the previous pending amounts first(by updating tbl_bills.paidamt and then what ever is left should be inserted as a brand new row in the same table.
HERE IS MY FAILED ATTEMPT :
THIS KEEPS ON RUNNING ENDLESSLY
declare #srno as int=0
declare #Cid as varchar(20)='C2001'
declare #PlanDuration as int=1
declare #Amount as money=800
declare #PlanDesc as varchar(20)='1MB'
declare #FromDate as datetime ='2014-11-11'
declare #ToDate as datetime='2014-12-11'
declare #PaidStatus as varchar(20)
declare #MkrId as varchar(20)='arbaaz'
declare #status as varchar(20)='PAID'
declare #Discount as money=0
declare #PaidAmt as money=1100
--as
if(#status='INSTALLED')
BEGIN
insert into tbl_bills (PlanDuration,Amount,PaidAmt,discount,PlanDesc,FromDate,ToDate,PaidStatus,MkrId,MkrDt,ServiceTax,TotalAmt,CustomerId)
values(#PlanDuration,#Amount,#paidamt,#discount,#plandesc,#FromDate,#ToDate,'PAID','Arbaaz',getdate(),#Amount*(12.36/100),#Amount+#Amount*(12.36/100),#Cid)
if((select sum(PendingAmt) from tbl_Bills where CustomerId=#cid)=0 )
begin
update tbl_installations set Status='PAID' ,ExpiryDate=#ToDate where CustomerId=#Cid
end
else
begin
update tbl_installations set Status='UNPAID' ,ExpiryDate=#ToDate where CustomerId=#Cid
end
END
ELSE
BEGIN
declare #pAmt as money
select #pAmt=sum(PendingAmt) from tbl_Bills where CustomerId=#Cid
declare #Amt as money =#Amount
select #Amt=#Amt
--select srno from tbl_Bills where CustomerId=#Cid and PendingAmt<>0 order by ToDate
if(#pAmt>0)
BEGIN------------------------
DECLARE #ColExpir datetime
DECLARE #ColFallprotec datetime
DECLARE #CurSrno int
--------------------------------------------------------
DECLARE #MyCursor CURSOR
SET #MyCursor = CURSOR FAST_FORWARD
FOR
select srno from tbl_Bills where CustomerId=#Cid and PendingAmt<>0 order by todate
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #CurSrno
WHILE ##FETCH_STATUS = 0
BEGIN
IF(#Amt>0)
BEGIN
declare #PendingAtCurSrno money
select #PendingAtCurSrno=pendingamt from tbl_Bills where SrNo=#CurSrno
print #CurSrno -----
print #PendingAtCurSrno ----
if(#Amt>#PendingAtCurSrno)
begin
update tbl_Bills set PaidAmt=TotalAmt where SrNo=#CurSrno
select #Amt=#Amt-#PendingAtCurSrno
print '1st'----
print #amt----
if(#amt=0)
begin
CLOSE #MyCursor --tried break and return here too
DEALLOCATE #MyCursor --
end
end
else
begin
update tbl_Bills set PaidAmt=paidamt+#Amt where SrNo=#CurSrno
select #Amt=0
print '2nd'
print #amt----
if(#amt=0)
begin
CLOSE #MyCursor --tried break and return here too
DEALLOCATE #MyCursor
end
end
END
END
FETCH NEXT FROM #MyCursor
INTO #PendingAtCurSrno
END
CLOSE #MyCursor
DEALLOCATE #MyCursor
END-------------------------
if(#Amt>0)
begin
insert into tbl_bills (PlanDuration,Amount,PaidAmt,discount,PlanDesc,FromDate,ToDate,PaidStatus,MkrId,MkrDt,ServiceTax,TotalAmt,CustomerId)
values(#PlanDuration,#Amount,#Amt,#discount,#plandesc,#FromDate,#ToDate,'PAID','Arbaaz',getdate(),#Amount*(12.36/100),#Amount+#Amount*(12.36/100),#Cid)
end
if((select sum(PendingAmt) from tbl_Bills where CustomerId=#cid)=0 )
begin
update tbl_installations set Status='PAID' ,ExpiryDate=#ToDate where CustomerId=#Cid
end
else
begin
update tbl_installations set Status='UNPAID' ,ExpiryDate=#ToDate where CustomerId=#Cid
end
Not only does it keep running endlessly , it keeps updating the paidamt over and over again and never gets to the point where it should insert another row with remaining amount.

Related

How to use batch separator inside Begin Try Catch SQL Server

I'm trying to create the SQL Script which needs to revert all the schema changes made if the error comes under any single SQL query. However, I'm trying to join both table and procedure under the same .sql file to run and try catch the error if present. It is working when i only uses the table, but when i try to add the procedure, it has some issue so added GO to separate table and procedure. But I can't able to Combine Begin try with GO statement.
BEGIN TRANSACTION
BEGIN TRY
Create TABLE [dbo].[Persons_1](
[PersonID] [int] NULL,
[LastName] [varchar](255) NULL,
[FirstName] [varchar](255) NULL,
[Address] [varchar](255) NULL,
[City] [varchar](255) NULL
) ON [PRIMARY] ;
Create TABLE [dbo].[Persons_2](
[PersonID] [int] NULL,
[LastName] [varchar](255) NULL,
[FirstName] [varchar](255) NULL,
[Address] [varchar](255) NULL,
[City] [varchar](255) NULL
) ON [PRIMARY] ;
CREATE PROCEDURE [dbo].[AAAtest]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Select statements for procedure here
Select * from Persons_1 ;
END;
COMMIT
END TRY
BEGIN CATCH
ROLLBACK;
THROW; -- Only if you want reraise an exception (to determine the reason of the exception)
END CATCH
You don't need go statements in a batch. What you can do is use an exec statement. I added a drop table and drop proc so the program can be rerun as much as you want:
BEGIN TRANSACTION
BEGIN TRY
DROP TABLE IF EXISTS [dbo].[Persons_1] ;
Create TABLE [dbo].[Persons_1](
[PersonID] [int] NULL,
[LastName] [varchar](255) NULL,
[FirstName] [varchar](255) NULL,
[Address] [varchar](255) NULL,
[City] [varchar](255) NULL
) ON [PRIMARY] ;
DROP TABLE IF EXISTS DBO.PERSONS_2;
Create TABLE [dbo].[Persons_2](
[PersonID] [int] NULL,
[LastName] [varchar](255) NULL,
[FirstName] [varchar](255) NULL,
[Address] [varchar](255) NULL,
[City] [varchar](255) NULL
) ON [PRIMARY] ;
DROP PROC IF EXISTS DBO.AAATEST;
DECLARE #TSQL VARCHAR(4000);
SET #TSQL = '
CREATE PROCEDURE [dbo].[AAAtest]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Select statements for procedure here
Select * from Persons_1 ;
END;'
EXEC (#TSQL);
COMMIT
END TRY
BEGIN CATCH
ROLLBACK;
THROW; -- Only if you want reraise an exception (to determine the reason of the exception)
END CATCH

Create a function to check if the quantity inserted is greater than the quantity in stock

CREATE TABLE [dbo].[OrderDetails](
[OrderID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[UnitPrice] [int] NOT NULL,
[Quantity] [tinyint] NULL,
[Discount] [int] NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL
) ON [PRIMARY]
I want to create a function which will check if the quantity inserted is greater then the quantity in stock then prevents user from execution.
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE TRIGGER dbo.PreventQtyInsert ON dbo.OrderDetails
AFTER INSERT
AS
BEGIN
DECLARE #returnQuantity INT ,
#Quantity INT ,
#ProductID INT ,
#GetQuantityFromProductsTable INT;
SELECT #returnQuantity = dbo.ReturnUnitsInStock ( #Quantity , #ProductID ) ;
IF #returnQuantity = 0
BEGIN
RAISERROR ( 'This vendor''s credit rating is too low to accept new purchase orders.' , 16 , 1 ) ;
ROLLBACK TRANSACTION;
RETURN;
END;
ELSE
BEGIN
SET #GetQuantityFromProductsTable = ( SELECT UnitsInStock FROM Products WHERE ProductID = #ProductID ) ;
UPDATE OrderDetails SET Quantity = #GetQuantityFromProductsTable - #Quantity
WHERE ProductID = #ProductID;
END;
END;
GO

Unable to generate tables after using convert for data transfer from XML to SQL Server

I am a little new at this so please bear with me. I am attempting to generate tables from an xml document. Due to some of the contents of the XML document I had to use the convert method, which I am not very familiar with. As a result I get an error. I am not sure why though. I am using Microsoft SQL Server 2016.
Here is my query:
WITH XmlFile (Contents) AS
(
SELECT
CONVERT (XML, BulkColumn,2)
FROM
OPENROWSET (BULK 'C:\Users\Owner\Documents\congress\House votes\114 congress 2015\passage\roll705.xml', SINGLE_BLOB) AS roll705
)
SELECT *
FROM XmlFile
GO
DECLARE #hdoc int
EXEC sp_xml_preparedocument #hdoc OUTPUT, xmlfile
SELECT *
FROM OPENXML (#hdoc, '/rollcall-vote/vote-metadata', 1)
WITH (
congress tinyint,
[session] char(3),
chamber varchar(40),
[rollcall-num] smallint,
[legis-num] varchar(20),
[vote-question] varchar(1000),
[vote-result] varchar (20),
[action-date] date,
[vote-desc] varchar(1000)
)
EXEC sp_xml_removedocument #hdoc
Here is a baby version of my XML document
<?xml-stylesheet type="text/xsl" href="http://clerk.house.gov/evs/vote.xsl"?>
<rollcall-vote>
<vote-metadata>
<majority>R</majority>
<congress>114</congress>
<session>1st</session>
<chamber>U.S. House of Representatives</chamber>
<rollcall-num>705</rollcall-num>
<legis-num>H R 2029</legis-num>
<vote-question>On Concurring in Senate Amdt with Amdt Specified in Section 3(a) of H.Res. 566</vote-question>
<vote-type>YEA-AND-NAY</vote-type>
<vote-result>Passed</vote-result>
<action-date>18-Dec-2015</action-date>
<action-time time-etz="09:49">9:49 AM</action-time>
<vote-desc>Making appropriations for military construction, the Department of Veterans Affairs, and related agencies for the fiscal year ending September 30, 2016, and for other purposes</vote-desc>
</rollcall-vote>
a picture of my error
UPDATE
This is where I am at now:
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[legislator],[state],[party],[vote],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],)
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''../maority[1]'',N''nvarchar(max)'')
,v.value(N''../congress[1]'',N''int'')
,v.value(N''../session[1]'',N''nvarchar(max)'')
,v.value(N''../chamber[1]'',N''nvarchar(max)'')
,v.value(N''../rollcall-num[1]'',N''int'')
,v.value(N''../legis-num[1]'',N''nvarchar(max)'')
,v.value(N''../vote-question[1]'',N''nvarchar(max)'')
,v.value(N''../vote-type[1]'',N''nvarchar(max)'')
,v.value(N''../vote-result[1]'',N''nvarchar(max)'')
,v.value(N''../action-date[1]'',N''nvarchar(max)'')
,v.value(N''../action-time[1]'',N''nvarchar(max)'')
,v.value(N''../vote-desc[1]'',N''nvarchar(max)'')
,#xml
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
this is a screenshot of my data in my folder
UPDATE
This is my query.
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + REPLACE(STR(#Counter,3),' ','0') + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],)
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''majority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
,#xml
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH print 'error'
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
UPDATE
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + REPLACE(STR(#Counter,3),' ','0') + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],)
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''majority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
,v.value(N''sourceXML[1]'',N''XML)'')
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH print 'error'
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
UPDATE
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + REPLACE(STR(#Counter,3),' ','0') + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],)
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''majority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
,#xml
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH print ERROR_MESSAGE()
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
NEW ERROR
update
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + REPLACE(STR(#Counter,3),' ','0') + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],[sourceXML])
SELECT ' +
',v.value(N''majority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
,#xml
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH print ERROR_MESSAGE()
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
ANOTHER UPDATE
CREATE TABLE [dbo].[staagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL,
[sourceXML] [XML] NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<800
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\Users\Owner\Documents\congress\House votes\114 congress 2015\Passage\roll' + REPLACE(STR(#Counter,3),' ','0') + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.staagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc],[sourceXML])
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''majority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
,#xml
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH print ERROR_MESSAGE()
END CATCH;
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.staagingTable;
GO
DROP TABLE dbo.staagingTable;
In the picture below you can see the error. The files that don't exist have the same old bulk file not found message. But the files that do exist (like 006, 012, and 014) have a different message.
As the essence of all your passed questions I pick
There are many xml files in the same directory (well, many in one and many in another)
All files have the same structure
You want to read them into a table
My Assumptions (which you have to adapt to your needs)
The names are computable (in my case "xml1", "xml2", "xml3" ...)
For my testscenario I created three XML files (called "xml1.xml", "xml2.xml" and "xml3.xml" with the content of your baby version. Therefore the loop stops at 4
Try this
I create a staging table with the fitting structure (do not bother about datetime conversion in this first step!)
I use a counter to compute the file's name within a loop
I use a WHILE loop
Within this loop the full statement is dynamically created. It will read your XML from the file into a variable and push all the values into the table.
With EXEC this command is executed
Check the result with a simple SELECT
This is the code
CREATE TABLE [dbo].[stagingTable](
[Counter] INT NOT NULL,
[majority] [nvarchar](max) NULL,
[congress] [int] NULL,
[session] [nvarchar](max) NULL,
[chamber] [nvarchar](max) NULL,
[rollcall-num] [int] NULL,
[legis-num] [nvarchar](max) NULL,
[vote-question] [nvarchar](max) NULL,
[vote-type] [nvarchar](max) NULL,
[vote-result] [nvarchar](max) NULL,
[action-date] [nvarchar](max) NULL,
[action-time] [nvarchar](max) NULL,
[vote-desc] [nvarchar](max) NULL
);
GO
DECLARE #Counter INT=1;
DECLARE #command VARCHAR(MAX);
WHILE #Counter<4
BEGIN
SET #command=
'
DECLARE #xml XML=
(
SELECT BulkColumn
FROM OPENROWSET (BULK ''C:\StackOverflow\xml' + CAST(#Counter AS VARCHAR(10)) + '.xml'', SINGLE_BLOB) AS c
);
INSERT INTO dbo.stagingTable(Counter,majority,congress,[session],chamber
,[rollcall-num],[legis-num],[vote-question],[vote-type]
,[vote-result],[action-date],[action-time],[vote-desc])
SELECT ' + CAST(#Counter AS VARCHAR(10)) +
',v.value(N''maority[1]'',N''nvarchar(max)'')
,v.value(N''congress[1]'',N''int'')
,v.value(N''session[1]'',N''nvarchar(max)'')
,v.value(N''chamber[1]'',N''nvarchar(max)'')
,v.value(N''rollcall-num[1]'',N''int'')
,v.value(N''legis-num[1]'',N''nvarchar(max)'')
,v.value(N''vote-question[1]'',N''nvarchar(max)'')
,v.value(N''vote-type[1]'',N''nvarchar(max)'')
,v.value(N''vote-result[1]'',N''nvarchar(max)'')
,v.value(N''action-date[1]'',N''nvarchar(max)'')
,v.value(N''action-time[1]'',N''nvarchar(max)'')
,v.value(N''vote-desc[1]'',N''nvarchar(max)'')
FROM #xml.nodes(N''/rollcall-vote/vote-metadata'') AS A(v);
';
EXEC(#command);
SET #Counter=#Counter+1;
END
SELECT * FROM dbo.stagingTable;
GO
DROP TABLE dbo.stagingTable;
UPDATE
If the file names are computeable, but there are gaps, just change the simple EXEC(#cmd) to this:
BEGIN TRY
EXEC(#command);
END TRY
BEGIN CATCH
--Might make sense to write some error meta data into a log table
END CATCH
This will ignore all file-not-found errors...

Cursor to fill data in table?

CREATE TABLE [dbo].[Table_A](
[ID] [int] IDENTITY(1,1) NOT NULL,
[AREA] [varchar](50) NOT NULL,
[Year] [int] NOT NULL,
[Month] [int] NOT NULL,
[Factor] [float] NULL,
[Net] [float] NULL,
[Path] [varchar](255) NULL,
[Created] [smalldatetime] NULL,
[CreatedBy] [varchar](50) NOT NULL,
[LastModified] [varchar](50) NOT NULL,
[LastModifiedBy] [varchar](50) NOT NULL)
)
ALTER TABLE [dbo].[Table_A] ADD DEFAULT ((1.0)) FOR [Factor]
GO
ALTER TABLE [dbo].[Table_A] ADD DEFAULT (sysdatetime()) FOR [Created]
GO
ALTER TABLE [dbo].[Table_A] ADD DEFAULT (suser_name()) FOR [CreatedBy]
GO
ALTER TABLE [dbo].[Table_A] ADD DEFAULT (sysdatetime()) FOR [LastModified]
GO
ALTER TABLE [dbo].[Table_A] ADD DEFAULT (suser_name()) FOR [LastModifiedBy]
GO
I need to fill up the Table using cursor where
cursor should fetch data from
Declare Cur_AREA Cursor
For
Select Distinct Media From DIM_AREA
Note:DIM_AREA CONSISTS OF texas,dallas,chicago and newark.
Cursor should fill data for years 1990 to 2020
My cursor code is::
Declare #Temp_Year int
Select #Temp_Year = MAX(Year)
While #Temp_Year < DATEPART(YEAR, GETDATE())
Begin
Declare Cur_Media Cursor
For
Select Distinct Media From DIM_AREA
Order by Media
open Cur_Media
Fetch Next From Cur_Media
While ##FETCH_STATUS = 0
Begin
Declare #Temp_Month int
Set #Temp_Month = 1
While #Temp_Month <= 12
Begin
Insert into Table_A (Media, Year, month)
Set #Temp_Month = #Temp_Month + 1
Set #Temp_Year = #Temp_Year + 1
end
end
Close Cur_Media
Deallocate Cur_Media
But my cursor not working properly :(
You may have other problems here, I don't think your question is fleshed out, but you say:
Insert into Table_A (Media, Year, month)
But you don't pick anything to be inserted.
Use:
Insert into Table_A (Media, Year, month)
VALUES('','','')
or:
Insert into Table_A (Media, Year, month)
SELECT '','',''
FROM YourTable
Replacing the empty quotes with whatever you are trying to insert.

How to call procedure for each row?

I have a Microsoft SQL Server R2 2008. And i see it first time in my life.
I have sql procedure:
DECLARE #RC int
DECLARE #Id uniqueidentifier
DECLARE #Segment_ID uniqueidentifier
DECLARE #SDate datetime
DECLARE #EDate datetime
DECLARE #withBig bit
DECLARE #withKm bit
DECLARE #withGeo bit
DECLARE #withDescr bit
-- TODO: задайте здесь значения параметров.
EXECUTE #RC = [Request_BusStation]
#Id
,#Segment_ID
,#SDate
,#EDate
,#withBig
,#withKm
,#withGeo
,#withDescr
GO
How i understand its just calling of procedure not thetself. But procedure too bit to copy it here.
AND have a table:
CREATE TABLE [BusStation](
[Id] [uniqueidentifier] NOT NULL,
[Segment_ID] [uniqueidentifier] NOT NULL,
[Dist] [decimal](18, 4) NOT NULL,
[Kod_Spr012] [smallint] NOT NULL,
[Square] [decimal](18, 6) NULL,
[OperationStartDate] [date] NULL,
[BallanceCost] [decimal](18, 6) NULL,
[DepreciatedCost] [decimal](18, 6) NULL,
[ChargesNorm] [decimal](18, 6) NULL,
[DocumentName] [varchar](100) NULL,
[DocumentNum] [varchar](100) NULL,
[DocumentDate] [date] NULL,
[Authority] [varchar](100) NULL,
[Kod_Spr091] [smallint] NOT NULL,
[HasWaysideStop] [bit] NOT NULL,
[HasLanding] [bit] NOT NULL,
[HasSpeedTransitArea] [bit] NOT NULL,
[LenSpeedTransitArea] [decimal](18, 6) NULL,
[YearBuilt] [smallint] NULL,
[YearMajorOverhaul] [smallint] NULL,
[Kod_Spr019] [smallint] NOT NULL,
[TechCond] [varbinary](max) NULL,
[LandCont] [varbinary](max) NULL,
[LandContDate] [date] NULL,
[LandContStartDate] [date] NULL,
[LandContEndDate] [date] NULL,
[Kod_Spr120] [smallint] NULL,
[E_Date_Begin] [datetime] NOT NULL,
[E_Date_End] [datetime] NULL,
[E_Date_Stop] [datetime] NULL,
Now i want to call this procedure for each row of table.
Its possible?
Yes, you can use a cursor that selects all the rows in the table and iteratively calls the stored procedure.
I would suggest that you may have a design issue before going down that route though. If the stored procedure needs to be called for every row in the table, you may be able to write a stored procedure that simply does what your current sp does to all the rows instead of a single row operation.
You have not provided what the sp is doing so I can only speculate here.
As mentioned in my comment, the only way I would know how to do that is using a CURSOR. Here is some sample code (untested of course):
DECLARE #ID INT
DECLARE #Segment_ID uniqueidentifier
DECLARE #getAccountID CURSOR
SET #BusStationCursor = CURSOR FOR
SELECT Id, Segment_ID --(etc: all the fields you need)
FROM BusStation
OPEN #BusStationCursor
FETCH NEXT FROM #BusStationCursor INTO #ID, #Segment_ID
WHILE ##FETCH_STATUS = 0
BEGIN
--CALL YOUR SP HERE
PRINT #ID
PRINT #Segment_ID
FETCH NEXT FROM #BusStationCursor INTO #ID, #Segment_ID
END
CLOSE #BusStationCursor
DEALLOCATE #BusStationCursor
This should help as well:
http://msdn.microsoft.com/en-us/library/ms180169.aspx
Good luck.