Slow stored procedure - SQL Server - mysql
So i have created a stored procedure to use within my VB.NET program. This checks if several tables exist and then creates the relevant tables and inserts data into them using other tables within the database. Originally my stored procedure was running quite well, but i have recently made some changes to it, and now it takes over 5 minutes to run, which is causing problems within the program i have made as the time delay causes it to freeze. Therefore i need to cut down the time it takes to execute the stored procedure. Below i have identified the two parts of the stored procedure that are taking a long time. These are:
Customers1 table
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customers1')
drop table Customers1
Create Table Customers1
(ID int identity(1,1),
[AccountNumber] NVARCHAR(20),
[AddressNo] int,
[Name] NVARCHAR(50),
[Address] NVARCHAR(50),
[Address2] NVARCHAR(50),
[Town] NVARCHAR(50),
[County] nvarchar(20),
[Postcode] nvarchar(15),
[Country] nvarchar(20),
[Contact] nvarchar(81),
[Phone] nvarchar(30),
[FaxNo] NVARCHAR(30),
[CurrentBalance] MONEY,
[CreditLimit] MONEY,
[Rep] NVARCHAR (50),
[EmailAddress] NVARCHAR(225),
[shiptoid] int default(0))
insert into Customers1([AccountNumber], [AddressNo],[Name],[Address],[Address2],[Town],[County],[Postcode],[Country],[Contact],[Phone],[FaxNo],[CurrentBalance],[CreditLimit],[Rep],[EmailAddress],[shiptoid])
select
[AccountNumber]
,0 as AddressNo
,[Company]
,[Address]
,[Address2]
,[city]
,[State]
,[ZIP]
,[Country]
,[FirstName]+ ' ' +[lastname]
,[PhoneNumber]
,[FaxNumber]
,[AccountBalance]
,[CreditLimit]
,case when customtext2 = '' then 'HOUSE' else customtext2 end AS Rep
,EmailAddress
,0
from customer
union all
select
[AccountNumber]
,0 as AddressNo
,shipto.[Company]
,shipto.[Address]
,shipto.[Address2]
,shipto.[city]
,shipto.[State]
,shipto.[ZIP]
,shipto.[Country]
,customer.[FirstName]+ ' ' +customer.[lastname]
,shipto.[PhoneNumber]
,shipto.[FaxNumber]
,customer.[AccountBalance]
,customer.[CreditLimit]
,case when customtext2 = '' then 'HOUSE' else customtext2 end AS Rep
,customer.EmailAddress
,shipto.id
from customer left join shipto
on customer.id= shipto.customerid
where shipto.company is not null
order by customer.accountnumber
declare #tableid int
declare #lasttableid int
declare #AccountNumber nvarchar(25)
declare #LineNumber int
set #tableID = 1
set #lasttableID = (select max([id]) from Customers1)
set #LineNumber = 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
while #tableID <= #lasttableid
begin
while #AccountNumber = (select AccountNumber from Customers1 where id = #tableid)
begin
update Customers1
set [AddressNo] = #LineNumber
where [id] = #tableid
set #LineNumber = #LineNumber + 1
set #tableid = #tableid + 1
end
set #LineNumber = 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
end
Orderlinehistory1 table
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OrderLineHistory1')
drop table OrderLineHistory1
Create Table OrderLineHistory1
(ID int identity(1,1),
[OrderNumber] nvarchar(25),
[LineNo] INT,
[ProductCode] nvarchar(25),
[DueDate] DATETIME,
[GrossSellingPrice] money,
[OrderedQty] float,
[DeliveredQty] float)
insert into OrderLineHistory1([OrderNumber],[LineNo],[ProductCode],[DueDate],[GrossSellingPrice],[OrderedQty],[DeliveredQty])
--select
--purchaseorder.ponumber
--,0 as [LineNo]
--,item.itemlookupcode
--,Purchaseorder.RequiredDate
--,item.price
--,purchaseorderentry.quantityordered
--,purchaseorderentry.quantityreceivedtodate
--from PurchaseOrder,PurchaseOrderEntry,item
--where PurchaseOrder.id = PurchaseOrderEntry.PurchaseOrderID
--and purchaseorderentry.itemid = item.id
--and purchaseorder.potype = 0
--order by purchaseorder.ponumber,purchaseorderentry.id
select
[orderentry].orderID
,0 as [LineNo]
,item.itemlookupcode
,[order].expirationorduedate
,orderentry.price
,orderentry.quantityonorder + orderentry.quantityRTD
,orderentry.quantityRTD
from orderentry left join [order] on orderentry.orderid = [order].ID
left join item on orderentry.itemid = item.id
where orderentry.orderid >= (select min([ordernumber]) from pastorders)
order by [orderentry].orderID, [orderentry].ID
declare #tableid1 int
declare #lasttableid1 int
declare #OrderNumber1 nvarchar(25)
declare #LineNumber1 int
set #tableID1 = 1
set #lasttableID1 = (select max([id]) from OrderLineHistory1)
set #LineNumber1 = 1
set #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
while #tableID1 <= #lasttableid1
begin
while #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
begin
update OrderLineHistory1
set [LineNo] = #LineNumber1
where [id] = #tableid1
set #LineNumber1 = #LineNumber1 + 1
set #tableid1 = #tableid1 + 1
end
set #LineNumber1 = 1
set #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
end
Can anybody think of a more efficient way of writing these? Thank you
The whole stored procedure:
ALTER Procedure sp_retreatHomes
AS
--SET NOCOUNT ON
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'FamilyCode')
drop table FamilyCode
Create Table FamilyCode
(ID int identity(1,1),
[Code] nvarchar(17),
[Name] nvarchar(30))
insert into FamilyCode([code],[name])
values ('Code','Name')
insert into FamilyCode([code],[name])
select Code,[name]
from category
union
select Code,[name]
from department
order by [name]
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customers1')
drop table Customers1
Create Table Customers1
(ID int identity(1,1),
[AccountNumber] NVARCHAR(20),
[AddressNo] int,
[Name] NVARCHAR(50),
[Address] NVARCHAR(50),
[Address2] NVARCHAR(50),
[Town] NVARCHAR(50),
[County] nvarchar(20),
[Postcode] nvarchar(15),
[Country] nvarchar(20),
[Contact] nvarchar(81),
[Phone] nvarchar(30),
[FaxNo] NVARCHAR(30),
[CurrentBalance] MONEY,
[CreditLimit] MONEY,
[Rep] NVARCHAR (50),
[EmailAddress] NVARCHAR(225),
[shiptoid] int default(0))
insert into Customers1([AccountNumber], [AddressNo],[Name],[Address],[Address2],[Town],[County],[Postcode],[Country],[Contact],[Phone],[FaxNo],[CurrentBalance],[CreditLimit],[Rep],[EmailAddress],[shiptoid])
select
[AccountNumber]
,0 as AddressNo
,[Company]
,[Address]
,[Address2]
,[city]
,[State]
,[ZIP]
,[Country]
,[FirstName]+ ' ' +[lastname]
,[PhoneNumber]
,[FaxNumber]
,[AccountBalance]
,[CreditLimit]
,case when customtext2 = '' then 'HOUSE' else customtext2 end AS Rep
,EmailAddress
,0
from customer
union all
select
[AccountNumber]
,0 as AddressNo
,shipto.[Company]
,shipto.[Address]
,shipto.[Address2]
,shipto.[city]
,shipto.[State]
,shipto.[ZIP]
,shipto.[Country]
,customer.[FirstName]+ ' ' +customer.[lastname]
,shipto.[PhoneNumber]
,shipto.[FaxNumber]
,customer.[AccountBalance]
,customer.[CreditLimit]
,case when customtext2 = '' then 'HOUSE' else customtext2 end AS Rep
,customer.EmailAddress
,shipto.id
from customer left join shipto
on customer.id= shipto.customerid
where shipto.company is not null
order by customer.accountnumber
declare #tableid int
declare #lasttableid int
declare #AccountNumber nvarchar(25)
declare #LineNumber int
set #tableID = 1
set #lasttableID = (select max([id]) from Customers1)
set #LineNumber = 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
while #tableID <= #lasttableid
begin
while #AccountNumber = (select AccountNumber from Customers1 where id = #tableid)
begin
update Customers1
set [AddressNo] = #LineNumber
where [id] = #tableid
set #LineNumber = #LineNumber + 1
set #tableid = #tableid + 1
end
set #LineNumber = 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
end
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CatalogueProducts1')
drop table CatalogueProducts1
Create Table CatalogueProducts1
(ID int identity(1,1),
[CatalogueCode] nvarchar(25),
[ProductCode] nvarchar(25),
[DisplaySequence] int)
insert into CatalogueProducts1([CatalogueCode],[ProductCode], [DisplaySequence])
SELECT case when left(SubDescription1,4) = '' then 'NA' else left(SubDescription1,4) end
,[ItemLookupCode]
,0
from dbo.Item
Order by left(SubDescription1,4) asc
declare #tableid2 int
declare #lasttableid2 int
declare #CatalogueCode nvarchar(25)
declare #DisplaySequence int
set #tableID2 = 1
set #lasttableID2 = (select max([id]) from CatalogueProducts1)
set #DisplaySequence = 1
set #CatalogueCode = (select CatalogueCode from CatalogueProducts1 where id = #tableid2)
while #tableID2 <= #lasttableid2
begin
while #CatalogueCode = (select CatalogueCode from CatalogueProducts1 where id = #tableid2)
begin
update CatalogueProducts1
set [DisplaySequence] = #DisplaySequence
where [id] = #tableid2
set #DisplaySequence = #DisplaySequence + 1
set #tableid2 = #tableid2 + 1
end
set #DisplaySequence = 1
set #CatalogueCode = (select CatalogueCode from CatalogueProducts1 where id = #tableid2)
end
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CatalogueProducts')
drop table CatalogueProducts
Create Table CatalogueProducts
(ID int identity(1,1),
[CatalogueCode] nvarchar(25),
[ProductCode] nvarchar(25),
[DisplaySequence] nvarchar(25))
insert into CatalogueProducts([CatalogueCode],[ProductCode], [DisplaySequence])
values('CatalogueCode','ProductCode', 'DisplaySequence')
insert into CatalogueProducts([CatalogueCode],[ProductCode], [DisplaySequence])
select CatalogueCode,ProductCode,convert(nvarchar,DisplaySequence)
from CatalogueProducts1
order by id
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'PastOrders')
drop table PastOrders
Create Table PastOrders
(ID int identity(1,1),
[OrderNumber] NVARCHAR(25),
[AccountCode] nvarchar(20),
[AddressNo] nvarchar(10),
[OrderDate] NVARCHAR(50),
[DueDate] NVARCHAR(50),
[RepCode] NVARCHAR(50))
insert into PastOrders([OrderNumber],[AccountCode],[AddressNo],[OrderDate],[DueDate],[RepCode])
values ('OrderNumber','AccountCode','AddressNo','OrderDate','DueDate','RepCode')
insert into PastOrders([OrderNumber],[AccountCode],[AddressNo],[OrderDate],[DueDate],[RepCode])
SELECT
CONVERT(VARCHAR,[Order].ID) AS OrderNumber
,Customer.AccountNumber
,case when shiptoid = 0 then 1 else shiptoid end AS AddressNo
,isnull(convert(nvarchar,(datepart(dd,[order].ExpirationOrDueDate)))
+ '/' + convert(nvarchar,(datepart(mm,[order].ExpirationOrDueDate)))
+ '/' + convert(nvarchar,(datepart(yy,[order].ExpirationOrDueDate))),'')
,isnull(convert(nvarchar,(datepart(dd,[order].LastUpdated)))
+ '/' + convert(nvarchar,(datepart(mm,[order].LastUpdated)))
+ '/' + convert(nvarchar,(datepart(yy,[order].LastUpdated))),'')
,case when customer.customtext2 = '' then 'HOUSE' else customer.customtext2 end
FROM [Order]
LEFT JOIN Customer ON [order].customerID = customer.ID
where Customer.AccountNumber is not null
and [order].[time] > (select getdate() - 550)
update PastOrders
set [AddressNo] = convert(nvarchar,customers1.addressno)
from PastOrders,customers1
where PastOrders.[AddressNo] = customers1.shiptoid
and PastOrders.[AddressNo] <> 'AddressNo'
update PastOrders
set [AddressNo] = 1
where [AddressNo] not in (select id from shipto)
and PastOrders.[AddressNo] <> 'AddressNo'
--fix customers
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customers')
drop table Customers
Create Table Customers
(ID int identity(1,1),
[AccountNumber] NVARCHAR(20),
[AddressNo] nvarchar(30),
[Name] NVARCHAR(50),
[Address] NVARCHAR(50),
[Address2] NVARCHAR(50),
[Town] NVARCHAR(50),
[County] nvarchar(20),
[Postcode] nvarchar(15),
[Country] nvarchar(20),
[Contact] nvarchar(81),
[Phone] nvarchar(30),
[FaxNo] NVARCHAR(30),
[CurrentBalance] NVARCHAR(225),
[CreditLimit] NVARCHAR(225),
[Rep] NVARCHAR (255),
[EmailAddress] NVARCHAR(225))
insert into Customers([AccountNumber], [AddressNo],[Name],[Address],[Address2],[Town],[County],[Postcode],[Country],[Contact],[Phone],[FaxNo],[CurrentBalance],[CreditLimit],[Rep],[EmailAddress])
values ('AccountNumber', 'AddressNo','Name','Address','Address2','Town','County','Postcode','Country','Contact','Phone','FaxNo','CurrentBalance','CreditLimit','Rep','EmailAddress')
insert into Customers([AccountNumber], [AddressNo],[Name],[Address],[Address2],[Town],[County],[Postcode],[Country],[Contact],[Phone],[FaxNo],[CurrentBalance],[CreditLimit],[Rep],[EmailAddress])
select [AccountNumber],
convert(nvarchar,[AddressNo])
,[Name]
,[Address]
,[Address2]
,[Town]
,[County]
,[Postcode]
,[Country]
,[Contact]
,[Phone]
,[FaxNo]
,convert(nvarchar,[CurrentBalance])
,convert(nvarchar,[CreditLimit])
,[Rep]
,[EmailAddress]
from customers1
order by [id] asc
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Products')
drop table Products
Create Table Products
(ID int identity(1,1),
[ProductCode] NVARCHAR(25),
[Description] NVARCHAR(30),
[UOM] NVARCHAR(4),
[Carton] NVARCHAR(30),
[StdPrice] NVARCHAR(25),
[SalesPrice] NVARCHAR(25),
[StockQty] NVARCHAR(25),
[PODueIn] NVARCHAR(25),
[OnSOQty] NVARCHAR(25),
[DueDate] NVARCHAR(25),
[Barcode] NVARCHAR(25),
[FamilyCode1] NVARCHAR(30),
[FamilyCode2] NVARCHAR(30))
insert into Products([ProductCode]
,[Description]
,[UOM]
,[Carton]
,[StdPrice]
,[SalesPrice]
,[StockQty]
,[PODueIn]
,[OnSOQty]
,[DueDate]
,[Barcode]
,[FamilyCode1]
,[FamilyCode2])
Values('ProductCode','Description','UOM','Carton','StdPrice','SalesPrice','StockQty','PODueIn','OnSOQty','DueDate','Barcode','FamilyCode1','FamilyCode2')
insert into Products([ProductCode]
,[Description]
,[UOM]
,[Carton]
,[Barcode]
,[StdPrice]
,[StockQty]
,[PODueIn]
,[OnSOQty]
,[DueDate]
,[FamilyCode1]
,[FamilyCode2]
,[SalesPrice])
select [ItemLookupCode]
,[Description]
,CASE [UnitOfMeasure] WHEN '' THEN 'EACH' ELSE UnitOfMeasure END AS UOM
,[SubDescription3]
, [Alias]
, convert(nvarchar,item.[Price])
, convert(nvarchar,item.[quantity])
, isnull(View_PO.PODueIn,0) as PODueIN
, convert(nvarchar,item.[QuantityCommitted])
, isnull(convert(nvarchar,(datepart(dd,View_PO.DueDate)))
+ '/' + convert(nvarchar,(datepart(mm,View_PO.DueDate)))
+ '/' + convert(nvarchar,(datepart(yy,View_PO.DueDate))),'') as DueDate
, isnull(department.[name],'') as Department
, isnull(category.[name],'') as Category
, convert(nvarchar,item.[SalePrice])
from Item
LEFT JOIN Alias ON alias.ItemID = Item.id
left join View_PO on item.id = View_PO.itemid
inner join firstAlias on alias.ID=firstAlias.id and firstAlias.ItemID=item.id
left join department on item.departmentid = department.id
left join category on item.categoryid = category.id
WHERE SubDescription3 NOT IN ('0','')
order by item.id asc
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OrderLineHistory1')
drop table OrderLineHistory1
Create Table OrderLineHistory1
(ID int identity(1,1),
[OrderNumber] nvarchar(25),
[LineNo] INT,
[ProductCode] nvarchar(25),
[DueDate] DATETIME,
[GrossSellingPrice] money,
[OrderedQty] float,
[DeliveredQty] float)
insert into OrderLineHistory1([OrderNumber],[LineNo],[ProductCode],[DueDate],[GrossSellingPrice],[OrderedQty],[DeliveredQty])
--select
--purchaseorder.ponumber
--,0 as [LineNo]
--,item.itemlookupcode
--,Purchaseorder.RequiredDate
--,item.price
--,purchaseorderentry.quantityordered
--,purchaseorderentry.quantityreceivedtodate
--from PurchaseOrder,PurchaseOrderEntry,item
--where PurchaseOrder.id = PurchaseOrderEntry.PurchaseOrderID
--and purchaseorderentry.itemid = item.id
--and purchaseorder.potype = 0
--order by purchaseorder.ponumber,purchaseorderentry.id
select
[orderentry].orderID
,0 as [LineNo]
,item.itemlookupcode
,[order].expirationorduedate
,orderentry.price
,orderentry.quantityonorder + orderentry.quantityRTD
,orderentry.quantityRTD
from orderentry left join [order] on orderentry.orderid = [order].ID
left join item on orderentry.itemid = item.id
where orderentry.orderid >= (select min([ordernumber]) from pastorders)
order by [orderentry].orderID, [orderentry].ID
declare #tableid1 int
declare #lasttableid1 int
declare #OrderNumber1 nvarchar(25)
declare #LineNumber1 int
set #tableID1 = 1
set #lasttableID1 = (select max([id]) from OrderLineHistory1)
set #LineNumber1 = 1
set #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
while #tableID1 <= #lasttableid1
begin
while #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
begin
update OrderLineHistory1
set [LineNo] = #LineNumber1
where [id] = #tableid1
set #LineNumber1 = #LineNumber1 + 1
set #tableid1 = #tableid1 + 1
end
set #LineNumber1 = 1
set #OrderNumber1 = (select OrderNumber from OrderLineHistory1 where id = #tableid1)
end
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OrderLineHistory')
drop table OrderLineHistory
Create Table OrderLineHistory
(ID int identity(1,1),
[OrderNumber] nvarchar(25),
[LineNo] nvarchar(25),
[ProductCode] nvarchar(25),
[DueDate] nvarchar(25),
[GrossSellingPrice]nvarchar(25),
[OrderedQty] nvarchar(25),
[DeliveredQty] nvarchar(25))
insert into OrderLineHistory([OrderNumber],[LineNo],[ProductCode],[DueDate],[GrossSellingPrice],[OrderedQty],[DeliveredQty])
values('OrderNumber','LineNo','ProductCode','DueDate','GrossSellingPrice','OrderedQty','DeliveredQty')
insert into OrderLineHistory([OrderNumber],[LineNo],[ProductCode],[DueDate],[GrossSellingPrice],[OrderedQty],[DeliveredQty])
select [OrderNumber],convert(varchar(25),[LineNo]),[ProductCode]
,isnull(convert(nvarchar,(datepart(dd,DueDate)))
+ '/' + convert(nvarchar,(datepart(mm,DueDate)))
+ '/' + convert(nvarchar,(datepart(yy,DueDate))),'')
,[GrossSellingPrice],[OrderedQty],[DeliveredQty]
from OrderLineHistory1
order by id asc
-- Reps
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Reps')
drop table Reps
Create Table Reps
(ID int identity(1,1),
[Code] nvarchar(17),
[Name] nvarchar(30))
insert into Reps([code],[Name])
values ('Code','Name')
insert into Reps([code],[Name])
select distinct customtext2,customtext2
from customer
where customtext2 <> ''
order by customtext2
--Catalogues
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Catalogues')
drop table Catalogues
Create Table Catalogues
(ID int identity(1,1),
[Code] nvarchar(17),
[Description] nvarchar(30))
insert into Catalogues([code],[Description])
values ('Code','Description')
insert into Catalogues([code],[Description])
select distinct left(subdescription1,4),subdescription1
from item
where subdescription1 <> ''
union
select 'NA', 'Not Assigned'
order by subdescription1
-- select * from reps
-- select * from Catalogues
-- select * from FamilyCode
-- select * from CatalogueProducts
-- select * from customers
-- select * from products
-- select * from pastorders
-- select * from orderlinehistory
I think you can re-write the looping logic just using one while loop. I can't say for sure as I don't know your exact business requirements and I can't test on any data. Try it and let me know:
set #tableID = 1
set #lasttableID = (select max([id]) from Customers1)
set #LineNumber = 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
while #AccountNumber = (select AccountNumber
from Customers1
where id = #tableid)
begin
update Customers1
set [AddressNo] = #LineNumber
where [id] = #tableid
set #LineNumber = #LineNumber + 1
set #tableid = #tableid + 1
set #AccountNumber = (select AccountNumber from customers1 where id = #tableid)
if (#tableId <= #lasttableid)
BREAK
else
CONTINUE
end
Related
SQL loop insert using declared table
I have a declared table which has a lot of data in it... I get the data by doing a select query on my InventoryLogs.. now, what I want is to insert this data on another table called MonthlySalesHistoryDetail... However I don't know how to get the values of my declared table... this is a stored procedure: Alter Procedure InsertMonthlySalesHistoryEndDate #CurrentDate date, #CreatedByID int, #LastInsertID int as Declare #details table ( RowID int identity(1,1) primary key, MonthlySalesHistoryID int, ItemID int, MeasurementUnitID int, QuantitySold numeric(18,4), QuantityReturned numeric(18,4), TotalSoldAmount numeric(18,4), TotalReturnedAmount numeric(18,4) ) Insert Into #details ( MonthlySalesHistoryID, ItemID, MeasurementUnitID, QuantitySold, QuantityReturned, TotalSoldAmount, TotalReturnedAmount ) SELECT #LastInsertID, il.ItemID, il.MeasurementUnitID, SUM(il.Quantity) as QuantitySold, ISNULL((SELECT SUM(Quantity) FROM InventoryLogs WHERE TransactionType = 15 AND CAST(InventoryLogDate as date) = #CurrentDate),0) as QuantityReturned, SUM(il.ComputedCost) as TotalSoldAmount, ISNULL((SELECT SUM(ComputedCost) FROM InventoryLogs WHERE TransactionType = 15 AND CAST(InventoryLogDate as date) = #CurrentDate),0) as TotalReturnedAmount FROM InventoryLogs il WHERE il.TransactionType = 9 AND CAST(InventoryLogDate as date) = #CurrentDate GROUP BY il.ItemID, il.MeasurementUnitID declare #count int = (SELECT COUNT(*) FROM #details) declare #counter int = 0 WHILE(#count > #counter) BEGIN SET #counter = #counter + 1 SELECT * FROM #details d Where d.RowID = #counter INSERT INTO MonthlySalesHistoryDetails ( MonthlySalesHistoryID, ItemID, MeasurementUnitID, QuantitySold, QuantityReturned, TotalSoldAmount, TotalReturnedAmount ) VALUES ( //I want to get the values of my //SELECT * FROM #details d Where d.RowID = #counter here.. ) END thanks in advance....
I didn't know that it was possible to do this insert... I thought it was only good for declared table INSERT INTO MonthlySalesHistoryDetails ( MonthlySalesHistoryID, ItemID, MeasurementUnitID, QuantitySold, QuantityReturned, TotalSoldAmount, TotalReturnedAmount ) SELECT d.MonthlySalesHistoryID, d.ItemID, d.MeasurementUnitID, d.QuantitySold, d.QuantityReturned, d.TotalSoldAmount, d.TotalReturnedAmount FROM #details d Where d.RowID = #counter
Rewrite Stored Procedure
I have the next stored procedure which inserts values into 2 tables. To the 2nd table I insert id's of 2 last inserts from 1st table However, I would like to rewrite it with one query instead of using temp table and while. CREATE PROCEDURE CurrencyExhange AS DECLARE #TmpTable Table ( ID int IDENTITY(1,1) NOT NULL PRIMARY KEY, BillID int, Amount decimal, Rate decimal, Date date ) INSERT INTO #TmpTable SELECT T.[BillID] ,[Amount] ,CR.Rate ,CR.Date FROM [FinanceLabkovich].[dbo].[Transactions] T JOIN [FinanceLabkovich].[dbo].Bills B ON B.BillID = T.BillID JOIN [FinanceLabkovich].[dbo].Currencies C ON C.CurrencyID=B.CurrencyID JOIN [FinanceLabkovich].[dbo].CurrencyRates CR ON CR.CurrencyRateID=FinanceLabkovich.dbo.GetRate(T.Date) WHERE LOWER(C.Name)='usd' AND T.Income=1 ORDER BY T.Date DECLARE #ToBillID int = (SELECT BillID FROM [FinanceLabkovich].[dbo].Bills B WHERE B.Name='Purse') DECLARE #i int = (SELECT MIN(Id) FROM #TmpTable) DECLARE #maxId int = (SELECT MAX(Id) FROM #TmpTable) DECLARE #TransactionID int, #ToTransactionID int, #Amount decimal DECLARE #date date WHILE (#i<=#maxId) BEGIN SET #date = (SELECT Date FROM #TmpTable WHERE ID=#i) SET #Amount = (SELECT AmountUSD FROM [FinanceLabkovich].[dbo].Cashflow WHERE Date=#date) IF #Amount > 0 BEGIN INSERT INTO [FinanceLabkovich].[dbo].[Transactions] (Name,BillID,ToBillID,Amount,Date,Income) SELECT "Name"='Currency exhange' ,BillID ,#ToBillID ,#Amount ,T.Date ,"Income"=0 FROM #TmpTable T WHERE ID=#i SET #TransactionID = ##IDENTITY INSERT INTO [FinanceLabkovich].[dbo].[Transactions] (Name,BillID,ToBillID,Amount,Date,Income) SELECT "Name"='Currency exhange' ,#ToBillID ,BillID ,#Amount*Rate AS Total ,Date ,"Income"=1 FROM #TmpTable WHERE ID=#i SET #ToTransactionID = ##IDENTITY INSERT INTO [FinanceLabkovich].[dbo].[Transfers] SELECT #TransactionID, #ToTransactionID END SET #i += 1 END Any help appreciated.
Convert one row of data in sql server to columns
I have a query that outputs just one row of data. I want to convert that row to column and the column to row. My original query ------------------------ ID Name Desc ------------------------ 1 Nisha Some desc what I need -------------------------- FieldName FieldValue -------------------------- ID 1 Name Nisha Description Some Desc
declare #colNum int, #i int = 1, #a nvarchar(4000) select #colNum=count(COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTable' set #a = ' declare #tempTable table ( slno int ,field nvarchar(100) ,value nvarchar(100) ) insert into #tempTable (slno,field) select ROW_NUMBER() over (order by ordinal_position asc),COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''YourTable'' declare #p nvarchar(100) ' declare #colname nvarchar(100) while #i<=#colNum begin select #colname =a.COLUMN_NAME from (select COLUMN_NAME,ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTable' )as a where a.ORDINAL_POSITION = #i set #a = #a + ' select #p='+#colname+' from YourTable update #tempTable set value = #p where slno = '+CONVERT(nvarchar(5), #i) +' ' set #i=#i+1 end set #a = #a + ' select * from #tempTable' declare #tempTable table ( slno int ,field nvarchar(100) ,value nvarchar(100) ) insert into #tempTable exec (#a) select * from YourTable select * from #tempTable
Need help to inserting 100 records in loop, continue where it stop from and break once the records are completed.
Need help to inserting 100 records in loop, continue where it stop from and break once the records are completed. Alter PROCEDURE ETL.ETLPurge #PurgeYear INT AS BEGIN DECLARE #BatchId INT = (SELECT BatchId FROM Tracker) declare #Count int declare #batchsize int set #batchsize = 100 --set #Count = ##rowcount SELECT DISTINCT IDENTITY(INT,1,1) AS ID, MC.ID INTO #tmp FROM Contact MC JOIN Extract CE ON MC.ExtractID = CE.ExtractID LEFT JOIN Application A ON MC.ID = A.ID WHERE CE.Year < #PurgeYear AND A.ApplicationId IS NULL --declare #counter bigint --set #counter = 1 --while #counter < 500 --Begin --while 1 = 1 --begin Create NONCLUSTERED INDEX nix_ID on #tmp(ID) --while 1=1 --begin INSERT --Top (#batchsize) INTO Table1 (Values ………) ( SELECT top (#batchsize) #BatchID, Values ……..) FROM Contact MC inner join #tmp TK on MC.ContactID = TK.ContactID --where TK.ID between #batchsize and #ctr + 1 ) if ##ROWCOUNT < #batchsize break end -- --continue -- --if ##ROWCOUNT = 0 -- Break end --end --number of rows inserted should equal number of rows deleted.
Ok. Here is my sample. What happened to me is that my dba "team" .. screwed up setting Replication for us. So .. over the weekend, working like dogs.... we had to write some code to "pull over" records from a source database to a destination database, where the structure of the database was the same. We had to fake-out some replication. We had 8,000,000 rows, and we would pull them over 10,000 at a time. Below, I have about 1000 rows, and set the "number of rows to pull at one time" to 333. I also put a #MaximumLoopCounter as a "just in case". I didn't want to accidentally create a endless loop. The sample below bases its "while" logic on "while exists (some records on the source-database-table that are not in the destination-database-table)"...keep grabbing those records. I'm trying to help you answer your question. In our case, we finally got replication working correctly, and we were able to abandon these scripts. It was NOT a fun weekend. /* SETUP */ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CodeCategorySourceTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN DROP TABLE [dbo].[CodeCategorySourceTable] END GO CREATE TABLE [dbo].[CodeCategorySourceTable] ( CodeCategoryUUID [uniqueidentifier] not null default NEWSEQUENTIALID() , CodeCategoryName varchar(64) not null ) GO ALTER TABLE [dbo].[CodeCategorySourceTable] ADD CONSTRAINT PK_CodeCategorySourceTable_CodeCategoryUUID PRIMARY KEY CLUSTERED (CodeCategoryUUID) GO ALTER TABLE [dbo].[CodeCategorySourceTable] ADD CONSTRAINT CK_CodeCategorySourceTable_CodeCategoryName_UNIQUE UNIQUE (CodeCategoryName) GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CodeCategoryDestinationTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN DROP TABLE [dbo].[CodeCategoryDestinationTable] END GO CREATE TABLE [dbo].[CodeCategoryDestinationTable] ( CodeCategoryUUID [uniqueidentifier] not null default NEWSEQUENTIALID() , CodeCategoryName varchar(64) not null ) GO ALTER TABLE [dbo].[CodeCategoryDestinationTable] ADD CONSTRAINT PK_CodeCategoryDestinationTable_CodeCategoryUUID PRIMARY KEY CLUSTERED (CodeCategoryUUID) GO ALTER TABLE [dbo].[CodeCategoryDestinationTable] ADD CONSTRAINT CK_CodeCategoryDestinationTable_CodeCategoryName_UNIQUE UNIQUE (CodeCategoryName) GO declare #AlreadyExistingCodeCategoryUUID01 uniqueidentifier declare #AlreadyExistingCodeCategoryUUID03 uniqueidentifier declare #AlreadyExistingCodeCategoryUUID02 uniqueidentifier declare #AlreadyExistingOldCodeCategoryName01 varchar(64) declare #AlreadyExistingOldCodeCategoryName02 varchar(64) declare #AlreadyExistingOldCodeCategoryName03 varchar(64) declare #AlreadyExistingNewCodeCategoryName01 varchar(64) declare #AlreadyExistingNewCodeCategoryName02 varchar(64) declare #AlreadyExistingNewCodeCategoryName03 varchar(64) select #AlreadyExistingCodeCategoryUUID01 = NEWID(), #AlreadyExistingCodeCategoryUUID02 = NEWID(), #AlreadyExistingCodeCategoryUUID03 = NEWID() select #AlreadyExistingNewCodeCategoryName01 = 'NewOne', #AlreadyExistingNewCodeCategoryName02 = 'NewTwo', #AlreadyExistingNewCodeCategoryName03 = 'NewThree' select #AlreadyExistingOldCodeCategoryName01 = 'OldOne', #AlreadyExistingOldCodeCategoryName02 = 'OldTwo', #AlreadyExistingOldCodeCategoryName03 = 'OldThree' Insert Into [dbo].[CodeCategorySourceTable] ( CodeCategoryUUID , CodeCategoryName ) Select top 1000 NEWID() , convert(varchar(40), NEWID()) + 'Name' from dbo.sysobjects so1 cross join dbo.sysobjects so2 Insert Into [dbo].[CodeCategorySourceTable] ( CodeCategoryUUID , CodeCategoryName ) select #AlreadyExistingCodeCategoryUUID01, #AlreadyExistingNewCodeCategoryName01 UNION ALL select #AlreadyExistingCodeCategoryUUID02, #AlreadyExistingNewCodeCategoryName02 UNION ALL select #AlreadyExistingCodeCategoryUUID03, #AlreadyExistingNewCodeCategoryName03 select count(*) from [dbo].[CodeCategorySourceTable] as CodeCategorySourceTableCOUNT Insert Into [dbo].[CodeCategoryDestinationTable] ( CodeCategoryUUID , CodeCategoryName ) select #AlreadyExistingCodeCategoryUUID01, #AlreadyExistingOldCodeCategoryName01 UNION ALL select #AlreadyExistingCodeCategoryUUID02, #AlreadyExistingOldCodeCategoryName02 UNION ALL select #AlreadyExistingCodeCategoryUUID03, #AlreadyExistingOldCodeCategoryName03 select count(*) from [dbo].[CodeCategoryDestinationTable] as CodeCategoryDestinationTableCOUNT /* USP */ print '[uspCodeCategoryReplicateReplacer]' go IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspCodeCategoryReplicateReplacer]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[uspCodeCategoryReplicateReplacer] Go /* declare #numberRowsAffected int declare #ErrorNumber int exec [dbo].[uspCodeCategoryReplicateReplacer] #numberRowsAffected output , #ErrorNumber output print #numberRowsAffected print #ErrorNumber print '' */ CREATE PROCEDURE [dbo].[uspCodeCategoryReplicateReplacer] ( #numberRowsAffected int output , #ErrorNumber int output ) AS SET NOCOUNT ON select #ErrorNumber = 0 declare #ErrorTracker int declare #insertRowCount int declare #updateRowCount int select #insertRowCount = 0 select #updateRowCount = 0 declare #CurrentInsertCount int declare #ManualReplicationRowCount int select #ManualReplicationRowCount = 333 declare #MaximumLoopCounter int select #MaximumLoopCounter = 10000 while (#MaximumLoopCounter > 0) and exists ( Select TOP 1 null from [dbo].[CodeCategorySourceTable] sourceTable with (nolock) where not exists ( select null from [dbo].[CodeCategoryDestinationTable] destinationTable with (nolock) Where destinationTable.CodeCategoryUUID = sourceTable.CodeCategoryUUID ) ) BEGIN select #MaximumLoopCounter = #MaximumLoopCounter - 1 /* DELETE FROM [dbo].[CodeCategoryDestinationTable] */ SET NOCOUNT OFF Insert into [dbo].[CodeCategoryDestinationTable] ( CodeCategoryUUID, CodeCategoryName ) Select TOP (#ManualReplicationRowCount) CodeCategoryUUID, CodeCategoryName from [dbo].[CodeCategorySourceTable] sourceTable with (nolock) where not exists ( select null from [dbo].[CodeCategoryDestinationTable] destinationTable with (nolock) Where destinationTable.CodeCategoryUUID = sourceTable.CodeCategoryUUID ) SELECT #CurrentInsertCount = ##ROWCOUNT , #ErrorTracker = ##ERROR select #insertRowCount = #insertRowCount + #CurrentInsertCount if #ErrorTracker <> 0 BEGIN select #ErrorNumber = #ErrorTracker select #MaximumLoopCounter = 0 /*Bail Out !!!*/ END SET NOCOUNT ON END /*End While Loop*/ print '/Before Look [dbo].[CodeCategoryDestinationTable] */' select * from [dbo].[CodeCategoryDestinationTable] SET NOCOUNT OFF /* A little extra. Update any non-surrogate-key values... We did not do this, but I leave it here as for kicks */ Update [dbo].[CodeCategoryDestinationTable] Set /*CodeCategoryUUID = vart.CodeCategoryUUID,*/ CodeCategoryName = sourceTable.CodeCategoryName From [dbo].[CodeCategoryDestinationTable] destinationTable, [dbo].[CodeCategorySourceTable] sourceTable Where /*Relationship*/ destinationTable.CodeCategoryUUID = sourceTable.CodeCategoryUUID /*Filter*/ and destinationTable.CodeCategoryName <> sourceTable.CodeCategoryName SELECT #updateRowCount = ##ROWCOUNT SET NOCOUNT ON print '/After Look [dbo].[CodeCategoryDestinationTable] */' select * from [dbo].[CodeCategoryDestinationTable] print '/#insertRowCount COUNT/' print #insertRowCount print '-------------------------' print '/#updateRowCount COUNT/' print #updateRowCount print '-------------------------' SELECT #numberRowsAffected = #insertRowCount + #updateRowCount print '/ [dbo].[CodeCategoryDestinationTable] COUNT/' print #numberRowsAffected print '-------------------------' SET NOCOUNT OFF GO /*GRANT EXECUTE ON dbo.uspCodeCategoryReplicateReplacer TO $(DBUSERNAME)*/ GO /* Improvement , encapsulate the ManualReplicationRowCount "getter" so it can be changed in one place */ IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspInternalSettingGetManualReplicationRowCount]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[uspInternalSettingGetManualReplicationRowCount] GO /* --START TEST declare #returnCode int declare #ManualReplicationRowCount int EXEC #returnCode = dbo.uspInternalSettingGetManualReplicationRowCount #ManualReplicationRowCount output print #ManualReplicationRowCount print '/#returnCode/' print #returnCode */ CREATE PROCEDURE [dbo].[uspInternalSettingGetManualReplicationRowCount] ( #ManualReplicationRowCount int output --return ) AS SET NOCOUNT ON select #ManualReplicationRowCount = 333 SET NOCOUNT OFF GO
What can I use instead of #Temp table in sql function
Here is my sql query. CREATE FUNCTION UF_GetOrderProducts ( #OrderId int ) RETURNS VARCHAR(500) AS BEGIN SELECT Identity(int,1,1) ID, ProductId INTO #Temp FROM OrderProduct WHERE OrderId = #OrderId Declare #Id int, #Count int, #LoopCount int, #ProductList VARCHAR(500), #ProductListTemp VARCHAR(500) SET #Count = (Select Count(*) From #Temp) SET #LoopCount = 1 SET #ProductList = '' WHILE #LoopCount <= #Count BEGIN SET #ProductListTemp =( SELECT Name FROM Product WHERE ProductId =(Select ProductId from #Temp Where ID = #LoopCount)) SET #ProductList +=#ProductListTemp + '<br/>' Set #LoopCount=#LoopCount + 1 END DROP TABLE #Temp RETURN #ProductList END GO I have to loop in #Temp Table. Do you have any other suggestions?
Instead of temp table you can use a table variable. declare #Temp TABLE (ID int identity, ProductId int) insert into #Temp(ProductId) select ProductId from OrderProduct where OrderId = #OrderId But you could rewrite your function without a loop. Something like this should do what you want. create function IF_GetOrderProducts ( #OrderId int ) returns varchar(500) as begin return ( select Name+'<br/>' from Product as P inner join OrderProduct as OP on P.ProductId = OP.ProductId where OP.OrderId = #OrderId for xml path(''), type ).value('.', 'varchar(500)') end