Update from select with join on same table - mysql

UPDATE inventory_audit_scans
SET inventory_audit_scans.inventory_item_id =
(SELECT id FROM (SELECT inventory_item.id as id
FROM inventory_item
RIGHT JOIN products
ON products.id = inventory_item.product_id
LEFT JOIN barcodes
ON barcodes.product_id = inventory_item.product_id
LEFT JOIN products_skus
ON products_skus.product_id = inventory_item.product_id
LEFT OUTER JOIN inventory_audit_scans ias
ON ias.inventory_item_id = inventory_item.id
AND ias.audit_report_id =
inventory_audit_scans.audit_report_id
WHERE ( products.sku LIKE inventory_audit_scans.text
OR barcodes.barcode LIKE inventory_audit_scans.text
OR products_skus.sku LIKE inventory_audit_scans.text
OR inventory_item.serial LIKE inventory_audit_scans.text )
AND inventory_item.store_id = in_store_id
AND inventory_audit_scans.inventory_item_id IS NULL
AND ( ( ( products.category_id =
inventory_audit_scans.category_id )
AND ( inventory_audit_scans.category_id IS NOT NULL ) )
OR ( ( ( products.category_id = 1 )
OR ( products.category_id = 2 ) )
AND inventory_audit_scans.category_id IS NULL ) )
ORDER BY inventory_item.id ASC
LIMIT 1) TmpTbl),
inventory_audit_scans.status_id = IF(inventory_audit_scans.inventory_item_id , 1 , 2) ,
updated = Now()
WHERE inventory_audit_scans.audit_report_id = 1
In the inner select where I get the error message
Error Code: 1054. Unknown column 'inventory_audit_scans.text' in 'where clause'
Is there any way i can access the actual row of the update statement in the enclosed SELECT to determine which would be the next available free ID which i not already used?
Before it tried it via the following method which takes approximately 3 minutes to "audit" 1600 records:
CREATE PROCEDURE `compareaudit`(IN audit_id INT(11))
BEGIN
DECLARE bDone INT DEFAULT 0;
DECLARE current_record_id INT(11) DEFAULT NULL;
DECLARE current_category_id INT(11) DEFAULT NULL;
DECLARE current_text VARCHAR(50) DEFAULT NULL;
DECLARE current_store_id INT(11) DEFAULT NULL;
DECLARE current_audit_id INT(11) DEFAULT NULL;
DECLARE res_inventory_item_id INT(11) DEFAULT NULL;
DECLARE res_serial VARCHAR(50) DEFAULT NULL;
DECLARE res_sku VARCHAR(20) DEFAULT NULL;
DECLARE res_barcode VARCHAR(30) DEFAULT NULL;
DECLARE res_product_skus VARCHAR(100) DEFAULT NULL;
DECLARE cur CURSOR FOR
SELECT `id`, `category_id`, `text`, `store_id`, `audit_report_id` FROM inventory_audit_scans WHERE audit_report_id = audit_id AND item_status IS NULL ORDER BY id ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
OPEN cur;
myloop:loop
FETCH cur INTO current_record_id, current_category_id, current_text, current_store_id, current_audit_id;
IF bDone = 1 THEN
leave myloop;
END IF;
call find_item(current_category_id, current_text, current_store_id, current_audit_id, res_inventory_item_id, res_serial, res_sku, res_barcode, res_product_skus);
IF (res_inventory_item_id IS NOT NULL) THEN
UPDATE inventory_audit_scans SET inventory_item_id = res_inventory_item_id, item_status = 1, updated = NOW() WHERE id = current_record_id;
END IF;
IF (res_inventory_item_id IS NULL) THEN
UPDATE inventory_audit_scans SET inventory_item_id = NULL, item_status = 2, updated = NOW() WHERE id = current_record_id;
END IF;
end loop myloop;
select true;
END
And:
CREATE PROCEDURE `find_item`(
IN in_category_id INT(11),
IN in_text VARCHAR(50),
IN in_store_id INT(11),
IN in_audit_id INT(11),
OUT my_inventory_item_id INT(11),
OUT my_serial VARCHAR(50),
OUT my_sku VARCHAR(20),
OUT my_barcode VARCHAR(30),
OUT my_product_skus VARCHAR(100))
BEGIN
SELECT inventory_item.id AS inventory_item_id,
inventory_item.`serial` AS `serial`,
products.sku AS SKU,
barcodes.barcode AS barcode,
products_skus.sku AS upc
INTO my_inventory_item_id,
my_serial,
my_sku,
my_barcode,
my_product_skus
FROM inventory_item
RIGHT JOIN products
ON products.id = inventory_item.product_id
LEFT JOIN barcodes
ON barcodes.product_id = inventory_item.product_id
LEFT JOIN products_skus
ON products_skus.product_id = inventory_item.product_id
LEFT OUTER JOIN inventory_audit_scans
ON inventory_audit_scans.inventory_item_id = inventory_item.id
AND inventory_audit_scans.audit_report_id = in_audit_id
WHERE (
products.sku LIKE in_text
OR barcodes.barcode LIKE in_text
OR products_skus.sku LIKE in_text
OR inventory_item.serial LIKE in_text )
AND inventory_item.store_id = in_store_id
AND inventory_audit_scans.inventory_item_id IS NULL
AND (
((products.category_id = in_category_id) AND (in_category_id IS NOT NULL))
OR
(((products.category_id = 1) OR (products.category_id = 2)) AND in_category_id IS NULL)
)
ORDER BY inventory_item.id ASC
LIMIT 1;
END

Related

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

case statement in where clause - SQL Server 2008

SELECT
PDADate, T.Merchandizer_ID, T.Merchandizer, Merchandizer_LoginName,
STORE_ID, STORE_CODE, STORE_NAME,
ACCOUNT_ID, ACCOUNT_NAME, Account_Store_Format_Id, Account_Store_Format,
StoreType_Id, StoreType, T.Listid, T.Listname,
T.TimeIn, T.TimeOut, T.PlannedDate, T.Reason, TaskCode, TotalTime
FROM
[dbo].Report_RD_Coverage T
INNER JOIN
#TempLocationH TL ON TL.LocationId=T.Location_Id
WHERE
CONVERT(Date, PDADate) Between (#Start_Date) AND Isnull(#End_Date, #CurrentDate)
AND T.Account_Id IN
(SELECT
CASE WHEN #Account_Id IS NULL THEN T.Account_Id
ELSE (SELECT * FROM UDF_SplitString(#Account_Id,','))
END
)
AND T.StoreType_Id IN
(SELECT
CASE WHEN #StoreType_Id IS NULL THEN T.StoreType_Id
ELSE (SELECT * FROM UDF_SplitString(#StoreType_Id,','))
END
)
AND T.Store_Id IN
(SELECT
CASE WHEN #Store_Id IS NULL THEN T.Store_Id
ELSE (SELECT * FROM UDF_SplitString(#Store_Id,','))
END
)
If #Account_Id, #StoreType_Id and #Store_Id are null the it should select all the ACCOUNT_ID, STORETYPE_ID and STORE_ID otherwise based on parameter value it should filter.
UDF_SplitString is the function to split up comma-separated strings, and its return value is a table like:
- 1
- 2
- 3
I'm getting this error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
CASE must return a scalar value, so try this variation instead:
select PDADate, T.Merchandizer_ID, T.Merchandizer, Merchandizer_LoginName, STORE_ID, STORE_CODE,
STORE_NAME, ACCOUNT_ID, ACCOUNT_NAME, Account_Store_Format_Id, Account_Store_Format,
StoreType_Id, StoreType, T.Listid, T.Listname, T.TimeIn, T.TimeOut, T.PlannedDate,
T.Reason, TaskCode, TotalTime
from [dbo].Report_RD_Coverage T
inner join #TempLocationH TL on TL.LocationId = T.Location_Id
where CONVERT(date, PDADate) between (#Start_Date)
and Isnull(#End_Date, #CurrentDate)
and (
#Account_Id is null
or T.Account_Id in (
select *
from UDF_SplitString(#Account_Id, ',')
)
)
and (
#StoreType_Id is null
or T.StoreType_Id in (
select *
from UDF_SplitString(#StoreType_Id, ',')
)
)
and (
#Store_Id is null
or T.Store_Id in (
select *
from UDF_SplitString(#Store_Id, ',')
) end
)
I tried this and reached very closer but you have to do something from what I found a link.
This is my try. the only thing you need to build is the #udf data.
declare #Store_Id INT;
declare #Account_Id INT;
DECLARE #UDF[9] OF VARCHAR(30);
set #Store_Id = 99 --NULL
set #Account_Id = 15
SET #UDF = '11,12,13,14,15,16'
SELECT #Account_Id AS ACID
WHERE CAST(#Account_Id AS VARCHAR(6)) IN (
CASE WHEN #Store_Id IS NULL THEN CAST(#Account_Id AS VARCHAR(6))
ELSE #UDF END
The link is at
http://www.codeproject.com/Questions/473174/CreateplusArrayplusinplusSqlplusServer
DECLARE #INSTR as VARCHAR(MAX)
SET #INSTR = '2,3,177,'
DECLARE #SEPERATOR as VARCHAR(1)
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
SET #SEPERATOR = ','
CREATE TABLE #tempTab (id int not null)
WHILE PATINDEX('%' + #SEPERATOR + '%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%' + #SEPERATOR + '%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #tempTab (id) VALUES (#VALUE)
END
SELECT * FROM myTable WHERE id IN **(SELECT id FROM #tempTab)**
DROP TABLE #tempTab
you can extract for the sql in bold and the logic how to create temp table and its data and I hope you will get what you want.
> This is the my right solultion........now its working correctly
CREATE TABLE #Store_Id (StoreID varchar(20))
IF #Store_Id != '0'
BEGIN
INSERT INTO #Store_Id
SELECT data FROM UDF_SplitString(#Store_Id,',')
END
ELSE
BEGIN
INSERT INTO #Store_Id
SELECT '0'
END
CREATE TABLE #StoreType_Id (StoreTypeID varchar(20))
IF #StoreType_Id != '0'
BEGIN
INSERT INTO #StoreType_Id
SELECT data FROM UDF_SplitString(#StoreType_Id,',')
END
ELSE
BEGIN
INSERT INTO #StoreType_Id
SELECT '0'
END
CREATE TABLE #Account_Id (AccountID varchar(20))
IF #Account_Id != '0'
BEGIN
INSERT INTO #Account_Id
SELECT data FROM UDF_SplitString(#Account_Id,',')
END
ELSE
BEGIN
INSERT INTO #Account_Id
SELECT '0'
END
INSERT INTO #FinalTable(VisitDate,Merchandizer_Id,Merchandizer,MerchandizerLogin,StoreId,StoreCode,StoreName,AccountId,AccountName,
Account_Store_Format_Id,Account_Store_Format,StoreTypeId ,StoreType ,ListId ,ListName,TimeIn ,TimeOut,PlannedDate ,Reason ,TaskCode,TotalTime)
SELECT Visit_Date,T.Merchandizer_ID,T.Merchandizer,Merchandizer_LoginName,STORE_ID,STORE_CODE,STORE_NAME,ACCOUNT_ID,ACCOUNT_NAME,
Account_Store_Format_Id,Account_Store_Format,StoreType_Id,
StoreType,T.Listid,T.Listname,T.TimeIn,T.TimeOut,T.PlannedDate,T.Reason,TaskCode,TotalTime
FROM [dbo].Report_RD_Coverage T
INNER JOIN #TempLocationH TL ON TL.LocationId=T.Location_Id
INNER JOIN #Store_Id on CONVERT(VARCHAR,t.Store_Id) = CASE WHEN #Store_Id = '0' THEN convert(VARCHAR,t.Store_Id) ELSE StoreID END
INNER JOIN #StoreType_Id on CONVERT(VARCHAR,t.StoreType_Id) = CASE WHEN #StoreType_Id = '0' THEN convert(VARCHAR,t.StoreType_Id) ELSE StoreTypeID END
INNER JOIN #Account_Id on CONVERT(VARCHAR,t.Account_Id) = CASE WHEN #Account_Id = '0' THEN convert(VARCHAR,t.Account_Id) ELSE AccountID END
WHERE CONVERT(Date,PDADate) Between #Start_Date AND #End_Date

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

Create LOG for tables in SQL Server

I have a table Sample and another SampleLog
With these structure I want to write codes to log. You can see my codes after structures of tables
CREATE TABLE [dbo].[Sample](
[ID] [int] NULL,
[Name] [varchar](10) NULL
)
CREATE TABLE [dbo].[SampleLog](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Date] [datetime] NULL,
[UserName] [varchar](100) NULL,
[Type] [char](1) NULL
)
I have written this code but it doesn't work for Delete and Update .
CREATE TRIGGER SampleTrigger ON Sample
AFTER INSERT, UPDATE, DELETE
AS
DECLARE
#ID int ,
#Name varchar(10),
#Date datetime,
#UserName VARCHAR(128) ,
#Type CHAR(1) ,
#sql nvarchar(500)
SELECT
#UserName = SYSTEM_USER ,
#Date = CONVERT(VARCHAR(8), GETDATE(), 112)
+ ' ' + CONVERT(VARCHAR(12), GETDATE(), 114)
IF EXISTS (SELECT * FROM inserted)
BEGIN
IF EXISTS (SELECT * FROM deleted)
BEGIN
SELECT #Type = 'U'
select #ID = ID from deleted
select #Name = Name from deleted
END
ELSE
BEGIN
SELECT #Type = 'I'
select #ID = ID from inserted
select #Name = Name from inserted
END
END
ELSE
BEGIN
SELECT #Type = 'D'
select #ID = ID from deleted
select #Name = Name from deleted
END
insert into SampleLog(ID, Name, Date, UserName, Type)
values(#ID, #Name, #Date, #UserName, #Type)
SQL Server gives me this error
The row values updateed or deleted either do not make the row unique or they alter multiple rows(2 rows)
You've coded for single row updates and deletes. Think sets!
CREATE TRIGGER SampleTrigger ON Sample after INSERT, UPDATE, DELETE
AS
SET NOCOUNT ON;
insert into SampleLog
(ID,Name,Date,UserName,Type)
SELECT
D.ID, D.NAME, GETDATE(), SYSTEM_USER,
CASE WHEN I.ID IS NULL THEN 'D' ELSE 'U' END
FROM
DELETED D
LEFT JOIN
INSERTED I ON D.ID = I.ID
UNION ALL
SELECT
I.ID, I.NAME, GETDATE(), SYSTEM_USER, 'I'
FROM
INSERTED I
LEFT JOIN
DELETED D ON D.ID = I.ID
WHERE
D.ID IS NULL
GO