Run large compare in Batches - sql

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

Related

SQL trigger not working in Azure Elastic DB

I have setup an Elastic Agent from Azure.
The elastic agent uses a db to maintain and work its logic in Azure.
The list of table which it creates is long. But this tables are what I am working on.
jobs_internal.job_exectutions (holds each run of the elastic job)
dbo.custom_status (table created to track activity of executions)
Table where DML operations will insert to dbo.custom_status schema
CREATE TABLE [dbo].[custom_status](
[Id] [int] IDENTITY(1,1) NOT NULL,
[job_id] [uniqueidentifier] NOT NULL,
[job_name] [nvarchar](128) NULL,
[job_execution_id] [uniqueidentifier] NOT NULL,
[start_time] [datetime] NULL,
[end_time] [datetime] NULL,
[lifecycle] [nvarchar](50) NULL,
[message] [nvarchar](max) NULL,
[exception] [nvarchar](max) NULL,
[column_state] [nvarchar](20) NOT NULL,
[entry_time] [datetime] NULL,
CONSTRAINT [PK_dbo.custom_status] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[custom_status] ADD DEFAULT (getdate()) FOR [entry_time]
GO
When I introduce trigger on the jobs_internal.job_executions on AFTER UPDATE, INSERT, DELETE
CREATE TRIGGER [jobs_internal].[TR_status_message]
ON [jobs_internal].[job_executions]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN TRY
DECLARE #activity NVARCHAR(20);
IF EXISTS (SELECT * FROM INSERTED) AND EXISTS (SELECT * FROM DELETED)
BEGIN
SET #activity = 'UPDATE';
INSERT INTO [dbo].[custom_status]
([job_id]
,[job_name]
,[job_execution_id]
,[start_time]
,[end_time]
,[lifecycle]
,[message]
,[exception]
,[column_state])
SELECT
org_job_exe.[job_id]
,(SELECT name
FROM jobs_internal.jobs
WHERE job_id = org_job_exe.job_id)
,org_job_exe.[job_execution_id]
,org_job_exe.[start_time]
,org_job_exe.[end_time]
,org_job_exe.[lifecycle]
,(SELECT message
FROM jobs_internal.job_task_executions
WHERE job_execution_id = org_job_exe.job_execution_id)
,(SELECT exception
FROM jobs_internal.job_task_executions
WHERE job_execution_id = org_job_exe.job_execution_id)
,#activity
FROM INSERTED as org_job_exe;
PRINT 'UPDATE operation failed in custom message trigger';
END;
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
SET #activity = 'DELETE';
INSERT INTO [dbo].[custom_status]
([job_id]
,[job_name]
,[job_execution_id]
,[start_time]
,[end_time]
,[lifecycle]
,[message]
,[exception]
,[column_state])
SELECT
org_job_exe.[job_id]
,(SELECT name
FROM jobs_internal.jobs
WHERE job_id = org_job_exe.job_id)
,org_job_exe.[job_execution_id]
,org_job_exe.[start_time]
,org_job_exe.[end_time]
,org_job_exe.[lifecycle]
,(SELECT message
FROM jobs_internal.job_task_executions
WHERE job_execution_id = org_job_exe.job_execution_id)
,(SELECT exception
FROM jobs_internal.job_task_executions
WHERE job_execution_id = org_job_exe.job_execution_id)
,#activity
FROM DELETED as org_job_exe;
PRINT 'DELETE operation failed in custom message trigger';
END;
BEGIN
SET #activity = 'INSERT';
INSERT INTO [dbo].[custom_status]
([job_id]
,[job_name]
,[job_execution_id]
,[start_time]
,[end_time]
,[lifecycle]
,[message]
,[exception]
,[column_state])
SELECT
org_job_exe.[job_id],
'test'
--,(SELECT name
--FROM jobs_internal.jobs
--WHERE job_id = org_job_exe.job_id)
,org_job_exe.[job_execution_id]
,org_job_exe.[start_time]
,org_job_exe.[end_time]
,org_job_exe.[lifecycle]
,'test'
--,(SELECT message
--FROM jobs_internal.job_task_executions
--WHERE job_execution_id = org_job_exe.job_execution_id)
,'test'
,#activity
FROM INSERTED as org_job_exe;
PRINT 'INSERT operation failed in custom message trigger';
END;
END TRY
BEGIN CATCH
PRINT 'Custom message trigger failed';
THROW;
END CATCH;
The trigger works but stops all the other CRUD operations/ DML operations on the base table stops causing the elastic jobs to not work and pile up in the queue.
There is already trigger created by ElasticJob server on this table and that is not stopping DML operations for the table
Hence, I tried it on a view
jobs.job_executions with DML of INSTEAD OF
ALTER TRIGGER [jobs].[TR_job_alert]
ON [jobs].[job_executions]
INSTEAD OF UPDATE
AS
BEGIN
--just to test normal is being triggered
insert custom_status
values (NEWID(),
'testing',
NEWID(),
null,
null,
'test',
null,
null,
'test',
GETDATE());
--INSERT INTO [dbo].[custom_status]
-- ([job_id]
-- ,[job_name]
-- ,[job_execution_id]
-- ,[start_time]
-- ,[end_time]
-- ,[lifecycle]
-- ,[message]
-- ,[exception]
-- ,[column_state])
--SELECT
-- org_job_exe.[job_id]
-- ,org_job_exe.[job_name]
-- ,org_job_exe.[job_execution_id]
-- ,org_job_exe.[start_time]
-- ,org_job_exe.[end_time]
-- ,org_job_exe.[lifecycle]
-- ,org_job_exe.[last_message]
-- ,null
-- ,#activity
--FROM inserted as org_job_exe
--BEGIN
-- SET #activity = 'INSERT';
-- INSERT INTO [dbo].[custom_status]
-- ([job_id]
-- ,[job_name]
-- ,[job_execution_id]
-- ,[start_time]
-- ,[end_time]
-- ,[lifecycle]
-- ,[message]
-- ,[exception]
-- ,[column_state])
-- SELECT
-- org_job_exe.[job_id]
-- ,(SELECT name
-- FROM jobs_internal.jobs
-- WHERE job_id = org_job_exe.job_id)
-- ,org_job_exe.[job_execution_id]
-- ,org_job_exe.[start_time]
-- ,org_job_exe.[end_time]
-- ,org_job_exe.[lifecycle]
-- ,(SELECT message
-- FROM jobs_internal.job_task_executions
-- WHERE job_execution_id = org_job_exe.job_execution_id)
-- ,(SELECT exception
-- FROM jobs_internal.job_task_executions
-- WHERE job_execution_id = org_job_exe.job_execution_id)
-- ,#activity
-- FROM inserted as org_job_exe
--END;
END;
GO
The trigger on the view never fires!
I know little bit of bulk DML operations won't fire triggers.
Is there something wrong with my trigger.
The fast trigger if it fires it will block all the other operations on table
The second trigger never fires on the view.
Try removing the PRINT statements. Long shot but maybe they are causing a hang that stops future processing.

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

updated record is inserting into the history table not the old record

i have two tables Test and TestHistory
CREATE TABLE [dbo].[TEST](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Test_History](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
INSERT INTO TEST ([ID],[Name],[Status],[CreatedDate])values (1,'Mohan','A',GETDATE())
Created Trigger :
ALTER TRIGGER [dbo].[trg_Test]
ON [dbo].[TEST]
FOR UPDATE
AS
Declare #ID INT;
Declare #Name varchar(10);
Declare #Status CHAR(2);
Declare #CreatedDate DATETIME;
Select #ID = I.ID from INSERTED I
Select #Name = I.Name from INSERTED I
Select #Status = I.Status from INSERTED I
Select #CreatedDate = I.CreatedDate from INSERTED I
INSERT INTO [dbo].[Test_history]
([ID]
,[Name]
,[Status]
,[CreatedDate]
)
SELECT #ID,
#Name,
#Status,
GETDATE()
FROM INSERTED I
WHERE #ID = [ID]
When I'm updating the record like
Update [TEST] SET Status = 'I' then the old record with Status = 'A' should inserted but the what ever i'm updating it has been inserting into Testhistory table not the old record
where i'm doing wrong and how to insert old value
like if i updating Status = 'I' and in history table Status = 'A' shoul be inserted
You need to INSERT from DELETED not from INSERTED.
See examples here Understanding SQL Server inserted and deleted tables for DML triggers.
Like Karl mentioned, you need to refer deleted table for old updated row information. Apart from that your existing code doesn't work when you update more than a single row. What you need is something like this.
ALTER TRIGGER [dbo].[trg_Test]
ON [dbo].[TEST]
FOR UPDATE
AS
INSERT INTO [dbo].[Test_history]
(
[ID],
[Name],
[Status],
[CreatedDate]
)
SELECT ID,
Name,
Status,
GETDATE()
FROM deleted d

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.

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.