What can I use instead of #Temp table in sql function - sql-server-2008

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

Related

Insert multiple entries into table using procedure in MySQL

I have created a procedure in mysql to insert into table as below.
DELIMITER $$
CREATE PROCEDURE createOrderPR ( IN iv_productID INT,
IN iv_orderDate DATE,
IN iv_orderTime TIME,
IN iv_shopID INT,
IN iv_mobileNo varchar(10),
IN iv_quantity smallint,
IN iv_total float(10,2),
IN iv_discount float(10,2),
IN iv_taxable float(10,2),
IN iv_CGST float(10,2),
IN iv_SGST float(10,2)
)
BEGIN
DECLARE availQty smallint default 0;
SELECT stockCount INTO availQty FROM product WHERE productID = iv_productID;
SET availQty = availQty - iv_quantity;
start transaction;
set autocommit =0;
INSERT INTO orders(orderNo,productID,orderDate,orderTime,shopID,mobileNo,quantity,total,discount,taxable,CGST,SGST,orderStatus,deletionMark)
VALUES( null,iv_productID,iv_orderDate,iv_orderTime,iv_shopID,iv_mobileNo,iv_quantity,iv_total,iv_discount,iv_taxable,iv_CGST,iv_SGST,'Open',null);
UPDATE product SET stockCount = availQty WHERE productID = iv_productID;
COMMIT;
SELECT MAX(orderNo) FROM orders WHERE shopID = shopID AND mobileNo = mobileNo;
END
$$
Currently it will only allow single record.now I need to insert multiple records in that case how to define the IN parameter of the procedure. Please suggest.
Solved the issue by using the JSON IN parameter these are the sample code (Note:new column added in the table rest all no change)
DELIMITER $$
CREATE PROCEDURE createOrderMulti ( IN orderJson JSON,
IN length INT )
BEGIN
-- Date Declaration
DECLARE availQty smallint default 0;
DECLARE iv_productID INT;
DECLARE iv_orderDate DATE;
DECLARE iv_orderTime TIME;
DECLARE iv_shopID INT;
DECLARE iv_mobileNo varchar(10);
DECLARE iv_quantity smallint;
DECLARE iv_total float(10,2);
DECLARE iv_discount float(10,2);
DECLARE iv_taxable float(10,2);
DECLARE iv_CGST float(10,2);
DECLARE iv_SGST float(10,2);
DECLARE counter smallint default 0;
DECLARE item INT;
DECLARE orderNo INT DEFAULT null;
start transaction;
set autocommit = 0;
WHILE counter < length DO
-- Extract the JSON value
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].productID')) INTO iv_productID;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].orderDate')) INTO iv_orderDate;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].orderTime')) INTO iv_orderTime;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].shopID')) INTO iv_shopID;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].mobileNo')) INTO iv_mobileNo;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].quantity')) INTO iv_quantity;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].total')) INTO iv_total;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].discount')) INTO iv_discount;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].taxable')) INTO iv_taxable;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].CGST')) INTO iv_CGST;
SELECT JSON_VALUE(orderJson, CONCAT('$[', counter, '].SGST')) INTO iv_SGST;
SELECT stockCount INTO availQty FROM product WHERE productID = iv_productID;
SET availQty = availQty - iv_quantity;
SET item = counter + 1;
INSERT INTO orders(orderNo,item,productID,orderDate,orderTime,shopID,mobileNo,quantity,total,discount,taxable,CGST,SGST,orderStatus,deletionMark)
VALUES( orderNo,item,iv_productID,iv_orderDate,iv_orderTime,iv_shopID,iv_mobileNo,iv_quantity,iv_total,iv_discount,iv_taxable,iv_CGST,iv_SGST,'Open',null);
SET orderNo = LAST_INSERT_ID();
UPDATE product SET stockCount = availQty WHERE productID = iv_productID;
SET counter = counter + 1;
END WHILE;
COMMIT;
--SELECT MAX(orderNo) FROM orders WHERE shopID = shopID AND mobileNo = mobileNo;
SELECT orderNo as orderNo;
END
$$

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.

Slow stored procedure - SQL Server

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

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