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

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

Related

Run large compare in Batches

I need to compare large tables with millions of rows and insert the differences into a log table.
The problem is that stored proc grows (LDF), and the database disk space is limited.
I know that commit will write the LDF to the MDF.
How can I perform the following compare in batches, and commit every hundred thousand rows?
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO dbo.CustomerLog
( OnlineStore ,
PhoneNumber ,
ChangeType
)
SELECT 'Online Store a' ,
AreaCode + PhoneNumber ,
'Added'
FROM dbo.StoreAList a
WHERE NOT EXISTS ( SELECT 1
FROM dbo.StoreAListCompare b
WHERE ( b.AreaCode + b.PhoneNumber ) = ( a.AreaCode
+ a.PhoneNumber ) );
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH;
CREATE TABLE [dbo].[StoreAList](
[ListID] [bigint] IDENTITY(1,1) NOT NULL,
[AreaCode] [char](3) NOT NULL,
[PhoneNumber] [char](7) NOT NULL,
[RecordDate] [datetime] NULL CONSTRAINT [DF_StoreAList_RecordDate] DEFAULT (getdate())
) ON [PRIMARY]
CREATE TABLE [dnc].[StoreAListCompare](
[ListID] [BIGINT] IDENTITY(1,1) NOT NULL,
[AreaCode] [CHAR](3) NOT NULL,
[PhoneNumber] [CHAR](7) NOT NULL,
[RecordDate] [DATETIME] NULL DEFAULT (GETDATE())
) ON [PRIMARY]
You can use the ##rowcount system variable and do the insert in batches until ##rowcount hits 0.
Note the added AND NOT EXISTS in dbo.CustomerLog...
Ex:
DECLARE #BATCHSIZE INT=100000
WHILE #BATCHSIZE>0
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO dbo.CustomerLog
( OnlineStore ,
PhoneNumber ,
ChangeType
)
SELECT TOP(#BATCHSIZE)
'Online Store a' ,
AreaCode + PhoneNumber ,
'Added'
FROM dbo.StoreAList a
WHERE NOT EXISTS ( SELECT 1
FROM dbo.StoreAListCompare b
WHERE ( b.AreaCode + b.PhoneNumber ) = ( a.AreaCode + a.PhoneNumber ) )
AND NOT EXISTS (SELECT 1
FROM dbo.CustomerLog CL
WHERE 'Online Store a'=CL.OnlineStore
AND AreaCode + PhoneNumber=CL.PhoneNumber
AND 'Added'=CL.ChangeType);
SET #BATCHSIZE=##ROWCOUNT
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SET #BATCHSIZE=0
END CATCH;
END

Log table using trigger

I need to create trigger which insert into dbo.Log table values:
- in action_type : how many records was UPDATED ,DELETED or INSERTED
- in datetime_of_action ofcourse timestamp of action
For now I have this:
DROP TABLE dbo.Log
CREATE TABLE dbo.Log (
logid INT NOT NULL IDENTITY,
action_type NVARCHAR(50) NOT NULL,
datetime_of_action DATETIME NOT NULL,
CONSTRAINT PK_Log PRIMARY KEY(logid));
CREATE TRIGGER trig2
ON Sales.Customers
FOR UPDATE , DELETE, INSERT
AS
BEGIN
......................
END
SELECT * FROM dbo.Log
And this is a script of Sales.Customers table:
CREATE TABLE [Sales].[Customers](
[custid] [int] IDENTITY(1,1) NOT NULL,
[companyname] [nvarchar](40) NOT NULL,
[contactname] [nvarchar](30) NOT NULL,
[contacttitle] [nvarchar](30) NOT NULL,
[address] [nvarchar](60) NOT NULL,
[city] [nvarchar](15) NOT NULL,
[region] [nvarchar](15) NULL,
[postalcode] [nvarchar](10) NULL,
[country] [nvarchar](15) NOT NULL,
[phone] [nvarchar](24) NOT NULL,
[fax] [nvarchar](24) NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[custid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
If anyone knows how do this I am open on your advice.
Use this query:
CREATE TRIGGER trig2
ON Sales.Customers
AFTER UPDATE , DELETE, INSERT
AS
BEGIN
IF EXISTS (select * From inserted)
BEGIN
IF EXISTS (select * From deleted)
BEGIN
INSERT INTO dbo.Log (action_typ, datetime_of_action )
VALUES(CAST(SELECT COUNT(*) FROM deleted) as VARCHAR(50) + ' records have been updated',GETDATE())
END
ELSE
BEGIN
INSERT INTO dbo.Log (action_typ, TOTAL, datetime_of_action )
VALUES(CAST(SELECT COUNT(*) FROM inserted) as VARCHAR(50) + ' records have been iniserted',GETDATE())
END
ELSE
BEGIN
INSERT INTO dbo.Log (action_typ, TOTAL, datetime_of_action )
VALUES(CAST(SELECT COUNT(*) FROM deleted) as VARCHAR(50) + ' records have been deleted',GETDATE())
END
END
CREATE TRIGGER trig2
ON Sales.Customers
FOR UPDATE , DELETE, INSERT
AS
BEGIN
SET NOCOUNT ON;
-- First determine the action
DECLARE #Action NVARCHAR(50);
SET #Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED)
THEN N'Update: ' + CAST( (SELECT COUNT(*) FROM INSERTED) AS NVARCHAR(10))
WHEN EXISTS(SELECT * FROM INSERTED) AND NOT EXISTS(SELECT * FROM DELETED)
THEN N'Insert: ' + CAST( (SELECT COUNT(*) FROM INSERTED) AS NVARCHAR(10))
WHEN EXISTS(SELECT * FROM DELETED) AND NOT EXISTS(SELECT * FROM INSERTED)
THEN N'Delete: ' + CAST( (SELECT COUNT(*) FROM DELETED) AS NVARCHAR(10))
ELSE NULL -- Skip. It may have been a "failed delete".
END)
INSERT INTO dbo.[Log] (action_type, datetime_of_action)
VALUES (#Action , GETDATE());
END

Sql stored procedure taking lot of time for execution

I am facing a big issue, the below stored procedure taking lot of time for execution. Please help me to find issues with following stored procedure .
We need to insert bulk subscriber list from excel in to database. But only 60 subscribers are getting inserted in to db in one minute.
Please help me to resolve the issue.
USE [SMS]
GO
/****** Object: StoredProcedure [dbo].[SP_ProcessFile] Script Date: 01/30/2015 12:56:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_ProcessFile]
#JobCode varchar(25)
WITH RECOMPILE
AS
declare
#jobCode1 Varchar(50),
#count int,#Code varchar(50),#Name [varchar](50),#Date Datetime,#Status int,
#i int,#EUCount int,#SubCount int,
#Add1 nvarchar(3000) ,
#Add2 nvarchar(500) ,
#Add3 nvarchar(500)
,#refdate [varchar](50) ,
#reference [varchar](50) ,
#Joined [varchar](50),
#Joinmonth [nvarchar](50),
#Activated [varchar](50),
#ActivMonth [nvarchar](50),
#Center [varchar](50) ,
#Region [varchar](50) ,
#Area [varchar](50) ,
#Modem [varchar](50) ,
#Adomstatus [varchar](50)
, #AddCode [varchar](50)
set #i = 1
Set #jobCode1 =#JobCode
BEGIN
SET NOCOUNT ON
Set #Status = (Select Distinct(status) from TSMST1005 where Jobcode = #jobCode1)
if (#Status = 0)
begin
Select '1' as res
end
else
begin
CREATE TABLE #tblSMS(pID int identity(1,1),
[Reference] [nvarchar](50) NULL,
[Date] [varchar](50) NOT NULL,
[Code] [nvarchar](50) NULL,
[Subname] [varchar](500) NULL,
[Address1] [nvarchar](3000) NULL,
[Address2] [nvarchar](500) NULL,
[Address3] [nvarchar](500) NULL,
[Joined] [varchar](50) NULL,
[Joinmonth] [varchar](50) NULL,
[Activated] [varchar](50) NULL,
[ActivMonth] [nvarchar](50) NULL,
[Center] [varchar](50) NULL,
[Region] [varchar](50) NULL,
[Area] [varchar](50) NULL,
[Modem] [varchar](50) NULL,
[Adomstatus] [varchar](50) NULL,
[RefDate] [varchar](50) NOT NULL)
insert into #tblSMS
SELECT Reference,[Date],
Code,Subname ,Address1 ,Address2 ,Address3 ,
Joined , Joinmonth ,Activated, ActivMonth ,
Center,Region,Area,Modem,Adomstatus ,refdate FROM TSMST1005 where jobcode = #jobCode1 and Status =1
WHILE #i <= (SELECT COUNT(*) FROM #tblSMS)
BEGIN
SELECT
#Code =Code,
#Name = Subname,
#Date =[Date],
#Add1 =Address1 ,
#Add2 =Address2 ,
#Add3= Address3,
#reference =Reference ,
#Joined = Joined,
#Joinmonth =Joinmonth,
#Activated =Activated,
#ActivMonth =ActivMonth,
#Center = Center,
#Region = Region,
#Area= Area,
#Modem = Modem ,
#Adomstatus =Adomstatus,
#refdate = RefDate
From #tblSMS where pID = #i
Insert into TCMST5001 (CompanyCode , Address1,Address2 ,Address3 ,CreatedDate ,Status) values('001',#Add1 ,#Add2,#Add3,GETDATE(),1)
Set #count = SCOPE_IDENTITY()
Set #AddCode = 'ADD' + Cast(#count As Varchar(10))
Update TCMST5001 Set Code =#AddCode Where AddressID =#count
Set #EUCount = (Select COUNT(*) from TCCOM0005 where EnterpriseUnitCode = #Center)
if (#EUCount = 0)
Begin
Insert into TCCOM0005(AddressCode,CompanyCode,EnterpriseUnitCode,EnterpriseUnitName,Status) values(#count ,'001',#Center,#Center ,1)
END
Set #SubCount = (Select COUNT(*) from TSMST1001 where Subscriber = #Code)
if (#SubCount =0)
begin
Insert into TSMST1001(ActivationDate ,refdate , Address ,AlternateName ,Area ,Region ,Subscriber,Name ,date ,CreatedDate ,EnterpriseUnit ,Status)
values(#Activated,#refdate ,#count ,#Name,#Area,#Region,#Code,#Name ,#Joined ,GETDATE(),#Center,#Adomstatus)
end
Insert into TSMST1003 (Device ,CreatedDate ,Subscriber,StartDate) values
(#Modem,GETDATE(),#Code,#Activated)
SET #i = #i + 1
Update TSMST1005 Set Status = 0 where Jobcode = #jobCode1
Select '3' as res
END
END
Drop table #tblSMS
end
It is quite hard to give you 100% working procedure. However your problem is that you are inserting records row by row. Instead of doing that you need to insert records in BULK. That would work A LOT faster. There is rewritten procedure. You still need to rewrite 2 inserts by the same logic. Of course there could be bugs as it is fully untested. Anyway, here we are:
USE [SMS]
GO
/****** Object: StoredProcedure [dbo].[SP_ProcessFile] Script Date: 01/30/2015 12:56:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_ProcessFile] #JobCode VARCHAR(25)
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON
SET #Status = ( SELECT TOP 1 status
FROM TSMST1005
WHERE Jobcode = #jobCode
)
IF ( #Status = 0 )
BEGIN
SELECT '1' AS res
END
ELSE
BEGIN
CREATE TABLE #tblSMS
(
pID INT IDENTITY(1, 1) ,
[Reference] [NVARCHAR](50) NULL ,
[Date] [VARCHAR](50) NOT NULL ,
[Code] [NVARCHAR](50) NULL ,
[Subname] [VARCHAR](500) NULL ,
[Address1] [NVARCHAR](3000) NULL ,
[Address2] [NVARCHAR](500) NULL ,
[Address3] [NVARCHAR](500) NULL ,
[Joined] [VARCHAR](50) NULL ,
[Joinmonth] [VARCHAR](50) NULL ,
[Activated] [VARCHAR](50) NULL ,
[ActivMonth] [NVARCHAR](50) NULL ,
[Center] [VARCHAR](50) NULL ,
[Region] [VARCHAR](50) NULL ,
[Area] [VARCHAR](50) NULL ,
[Modem] [VARCHAR](50) NULL ,
[Adomstatus] [VARCHAR](50) NULL ,
[RefDate] [VARCHAR](50) NOT NULL
)
INSERT INTO #tblSMS
SELECT Reference ,
[Date] ,
Code ,
Subname ,
Address1 ,
Address2 ,
Address3 ,
Joined ,
Joinmonth ,
Activated ,
ActivMonth ,
Center ,
Region ,
Area ,
Modem ,
Adomstatus ,
RefDate
FROM TSMST1005
WHERE jobcode = #jobCode1
AND Status = 1
WHILE #i <= ( SELECT COUNT(*)
FROM #tblSMS
)
BEGIN
DECLARE #minPK INT;
SELECT #minPK = MAX(AddressID ) FROM TCMST5001; -- I believe that it is identity column. If not change it to the proper one
INSERT INTO TCMST5001
( CompanyCode ,
Address1 ,
Address2 ,
Address3 ,
CreatedDate ,
Status
)
SELECT '001', Address1, Address2, Address3, GETDATE(), 1 FROM #tblSMS;
SET #AddCode = 'ADD' + CAST(#count AS VARCHAR(10))
UPDATE TCMST5001
SET Code = 'ADD' + CAST(AddressID AS VARCHAR(10))
WHERE AddressID > #minPK ;
INSERT INTO TCCOM0005
SELECT ee.cnt, t.center, t.Center, 1
FROM #tblSMS t
CROSS APPLY ( SELECT COUNT(*) AS cnt FROM TCCOM0005 e WHERE e.EnterpriseUnitCode = t.Center) ee
WHERE ee.cnt > 0
-- THE SAME LOGIC MUST BE DONE WITH THESE 2 INSERTS
SET #SubCount = ( SELECT COUNT(*)
FROM TSMST1001
WHERE Subscriber = #Code
)
IF ( #SubCount = 0 )
BEGIN
INSERT INTO TSMST1001
( ActivationDate ,
refdate ,
Address ,
AlternateName ,
Area ,
Region ,
Subscriber ,
Name ,
date ,
CreatedDate ,
EnterpriseUnit ,
Status
)
VALUES ( #Activated ,
#refdate ,
#count ,
#Name ,
#Area ,
#Region ,
#Code ,
#Name ,
#Joined ,
GETDATE() ,
#Center ,
#Adomstatus
)
END
INSERT INTO TSMST1003
( Device ,
CreatedDate ,
Subscriber ,
StartDate
)
VALUES ( #Modem ,
GETDATE() ,
#Code ,
#Activated
)
UPDATE t
FROM TSMST1005 t
SET Status = 0
JOIN #tblSMS tmp
ON tmp.jobCode1 = t.Jobcode
SELECT '3' AS res
END
END
DROP TABLE #tblSMS
END
some tips will be. Avoid doing this in every step.
SELECT COUNT(*) FROM #tblSMS
instead assign the count value to a local variable, and check the i against the same.
Also you are selecting values from these tables ( TCCOM0005, TSMST1001, TSMST1003 ) frequently , It will be good to check if these tables have proper indexes.

Unable to exit Sql cursor

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.

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.