I have a Table TBLmaterial where current Stock is defined for particular Materailid .
And i have a tbldrawingtable where required quantity is listed for a particular material . It should update present column as required quantity and status to Available if current stock is available .
for example : Materialid =2 have 4 requiredQTY in 102=drawid and 2 requiredQTY in 105=drawid . IT should update because total 6 CurrentStock is present for the material id 2.
As per latest update of code .below result will displayed which is correct.
If i check for material id 1 once again . it should update drawing id 107 for the material id 1 to Not available because no more current stock is available to update .
my code below :
Alter procedure dbo.FetchInto(#Matid int)
as
begin
declare #CurrentStock int
declare #required Int
declare #present int
select #CurrentStock=M.CurrentStock
from Tblmaterial M
inner join
TblDrawingTable D
on M.Matid=D.Matid
where M.Matid =#Matid
select top 1 #required=d.RequiredQty from Tblmaterial M
inner join
TblDrawingTable D
on M.Matid=D.Matid
where m.Matid =#Matid
select top 1 #present=(m.CurrentStock-isnull(d.Present,0))
from TblDrawingTable D
inner join
Tblmaterial M
on D.Matid=m.Matid
where D.Matid=#Matid
if exists(select 1 from TblDrawingTable where Matid=#Matid and Present is
null)
begin
if (#required<=#CurrentStock and #present >0)
UPDATE TblDrawingTable SET present=#required,status='Available' where Drawid
= (select top 1 Drawid from TblDrawingTable where
Matid=#Matid) and Matid=#Matid
end
else if(#present=#required)
update TblDrawingTable SET status='Not Available',Present=#present where
Drawid <> (select top 1 Drawid from TblDrawingTable where
Matid=#Matid) and Matid=#Matid
if exists(select 1 from TblDrawingTable where Matid=#Matid and Present is
null)
begin
if (#required<=#CurrentStock and #present>0)
UPDATE TblDrawingTable SET present=(#CurrentStock-
#required),status='Available' where Drawid <> (select top 1 Drawid from
TblDrawingTable where
Matid=#Matid) and Matid=#Matid
end
else if(#present=#required)
update TblDrawingTable SET status='Not Available',Present=#present where
Matid=#Matid
end
I didn't check your code, but if I understood correctly you need to:
collect all the existing material from drawings
compare with in stock
update consequentially
I would work with CTE
Edit:
I add some partial code that can be used to solve the issue
;WITH ExistingMat AS (
SELECT Matid, SUM(RequiredQty) ExistingQty
FROM TBLDrawing
GROUP BY Matid
),
CompareMat AS (
SELECT m.*, ISNULL(e.ExistingQty, 0) ExistingQty
FROM TBLMaterial m LEFT OUTER JOIN ExistingMat e ON m.Matid = e.Matid
)
SELECT d.*, c.CurrentStock, c.ExistingQty, CASE WHEN c.ExistingQty <= c.CurrentStock THEN 'Available' ELSE 'Not Available' END UpdStatus, ExistingQty UpdPresent
FROM TBLDrawing d INNER JOIN CompareMat c ON d.Matid = c.Matid
Related
I'm having trouble understanding why this query is not working. I get a message
The table '#PriceChanges' is ambiguous
The first mention of #PriceChanges is underlined
UPDATE #PriceChanges
SET MaxQty = MIN(ISNULL(PT.MinQty, 100000000))
FROM #PriceChanges P
LEFT JOIN #PriceChanges PT ON P.ChangeType = PT.ChangeType
AND P.ItemNo = PT.ItemNo
AND P.MinQty < PT.MinQty
So what I'm trying to achieve is setting the MAX quantity of a given line to the next MIN quantity found in the same table. If there's none found, then just make it a ridiculously high number (100,000,000)
The end result should look like something like this
MinQty MaxQty
-----------------
0 20
20 50
50 100
100 100000000
The ambiguity arises because the FROM clause of the UPDATE refers to the #PriceChanges table twice, so there is no way for SQL Server to know which of the two you intend to update. To resolve the ambiguity, instead of writing UPDATE #PriceChanges, use UPDATE P or UPDATE PT. Here's a trivial example:
create table #Test (id int, datum char(1));
insert #Test values (1, ' '), (2, ' ');
-- ERROR: The table '#Test' is ambiguous.
update #Test set datum = 'X' from #Test T1 inner join #Test T2 on T1.id = T2.id + 1;
-- CORRECT: Use the appropriate table alias to indicate which instance of #Test you want to update.
update T1 set datum = 'X' from #Test T1 inner join #Test T2 on T1.id = T2.id + 1;
Creating an intermediary table worked, I still wonder why this couldn't all be put into a single update
SELECT P.ChangeType, P.ItemNo, P.MinQty, MIN(PT.MinQty) AS MaxQty
INTO #MaxQty
FROM #PriceChanges P
LEFT JOIN #PriceChanges PT
ON P.ChangeType = PT.ChangeType
AND P.ItemNo = PT.ItemNo
AND P.MinQty < PT.MinQty
GROUP BY P.ChangeType, P.ItemNo, P.MinQty
UPDATE #PriceChanges
SET MaxQty = ISNULL(PM.MaxQty, 100000000)
FROM #PriceChanges P
LEFT JOIN #MaxQty PM
ON P.ChangeType = PM.ChangeType
AND P.ItemNo = PM.ItemNo
AND P.MinQty = PM.MinQty
I see no use for ISNULL(PT.MinQty, 100000000). MIN() ignores NULL values. And you don't need a self join. An updatable CTE or subquery works:
UPDATE pc
SET MaxQty = min_minqty
FROM (SELECT pc.*, MIN(pc.MinQty) OVER (PARTITION BY ItemNo, ChangeType) as min_minqty
FROM #PriceChanges pc
) pc
WHERE pc.MaxQty <> min_minqty;
EDIT:
You appear to want:
with pc as (
select pc.*,
lead(pc.MinQty) over (order by pc.MinQty) as next_MinQty
from #PriceChanges pc
)
update pc
set MaxQty = next_MinQty;
First when I started this project seemed very simple. Two tables, field tbl1_USERMASTERID in Table 1 should be update from field tbl2_USERMASTERID Table 2. After I looked deeply in Table 2, there is no unique ID that I can use as a key to join these two tables. Only way to match the records from Table 1 and Table 2 is based on FIRST_NAME, LAST_NAME AND DOB. So I have to find records in Table 1 where:
tbl1_FIRST_NAME equals tbl2_FIRST_NAME
AND
tbl1_LAST_NAME equals tbl2_LAST_NAME
AND
tbl1_DOB equals tbl2_DOB
and then update USERMASTERID field. I was afraid that this can cause some duplicates and some users will end up with USERMASTERID that does not belong to them. So if I find more than one record based on first,last name and dob those records would not be updated. I would like just to skip and leave them blank. That way I wouldn't populate invalid USERMASTERID. I'm not sure what is the best way to approach this problem, should I use SQL or ColdFusion (my server side language)? Also how to detect more than one matching record?
Here is what I have so far:
UPDATE Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
Here is query where I tried to detect duplicates:
SELECT DISTINCT
tbl1.FName,
tbl1.LName,
tbl1.dob,
COUNT(*) AS count
FROM Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.FName = tbl2.first
AND tbl1.LName = tbl2.last
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND LTRIM(RTRIM(tbl1.first)) <> ''
AND LTRIM(RTRIM(tbl1.last)) <> ''
AND LTRIM(RTRIM(tbl1.dob)) <> ''
GROUP BY tbl1.FName,tbl1.LName,tbl1.dob
Some data after I tested query above:
First Last DOB Count
John Cook 2008-07-11 2
Kate Witt 2013-06-05 1
Deb Ruis 2016-01-22 1
Mike Bennet 2007-01-15 1
Kristy Cruz 1997-10-20 1
Colin Jones 2011-10-13 1
Kevin Smith 2010-02-24 1
Corey Bruce 2008-04-11 1
Shawn Maiers 2016-08-28 1
Alenn Fitchner 1998-05-17 1
If anyone have idea how I can prevent/skip updating duplicate records or how to improve this query please let me know. Thank you.
You could check for and avoid duplicate matches using with common_table_expression (Transact-SQL)
along with row_number()., like so:
with cte as (
select
t.fname
, t.lname
, t.dob
, t.usermasterid
, NewUserMasterId = t2.usermasterid
, rn = row_number() over (partition by t.fname, t.lname, t.dob order by t2.usermasterid)
from table1 as t
inner join table2 as t2 on t.dob = t2.dob
and t.fname = t2.fname
and t.lname = t2.lname
and ltrim(rtrim(t.usermasterid)) = ''
)
--/* confirm these are the rows you want updated
select *
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
/* update those where only 1 usermasterid matches this record
update t
set t.usermasterid = t.NewUserMasterId
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
I use the cte to extract out the sub query for readability. Per the documentation, a common table expression (cte):
Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.
Using row_number() to assign a number for each row, starting at 1 for each partition of t.fname, t.lname, t.dob. Having those numbered allows us to check for the existence of duplicates with the not exists() clause with ... and i.rn>1
You could use a CTE to filter out the duplicates from Table1 before joining:
; with CTE as (select *
, count(ID) over (partition by LastName, FirstName, DoB) as IDs
from Table1)
update a
set a.ID = b.ID
from Table2 a
left join CTE b
on a.FirstName = b.FirstName
and a.LastName = b.LastName
and a.Dob = b.Dob
and b.IDs = 1
This will work provided there are no exact duplicates (same demographics and same ID) in table 1. If there are exact duplicates, they will also be excluded from the join, but you can filter them out before the CTE to avoid this.
Please try below SQL:
UPDATE Table1 AS tbl1
INNER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
LEFT JOIN Table2 AS tbl3
ON tbl3.dob = tbl2.dob
AND tbl3.fname = tbl2.fname
AND tbl3.lname = tbl2.lname
AND tbl3.usermasterid <> tbl2.usermasterid
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND tbl3.usermasterid is null
Trying to get the select case statement to control whether nothing happens or a table is updated based on the sum of three fields from two different tables. One of the tables is a temp table (#tempGLsum). This holds the id field and the sum amount. The "amt" field in the tblPcardGL table should never go below 0 (zero). If it would, then the flow should stop. If it will still be > 0, then the next block of code would run, which updates the tblPcardGL table.
Any assistance would be appriciated!
Thanks
declare #glID int
create table #tempGLsum
(glID int, sumAmt decimal(18,2))
insert into #tempGLsum
(glID, sumAmt)
select tblPcardReclass.glID,
sum(tblPcardReclass.reclassAmt)
from tblPcardReclass
where tblPcardReclass.glID = #glID
group by tblPcardReclass.glID
select
case when (tblPcardGL.orgAmt - tblPcardGL.amt - #tempGLsum.sumAmt) < 0
then 'stop here and let the user know it's below zero'
else
'run the code_below'
end
from tblPcardGL
left outer join #tempGLsum ON
tblPcardGL.glID = #tempGLsum.glID
where tblPcardGL.glID = #glID
-- code_below
update tblPcardGL
set amt =
(
select
case (select COUNT(*) as numRecs from #tempGLsum)
when 0 then
tblPcardGL.orgAmt
else
(tblPcardGL.orgAmt - #tempGLsum.sumAmt)
end
)
from tblPcardGL
left outer join #tempGLsum ON
tblPcardGL.glID = #tempGLsum.glID
where tblPcardGL.glID = #glID
You can't really do what you want with a case statement. You just have to do it in two steps:
First run the select with a where clause to show the user all the problems:
select tblPcardGL.*, 'Below Zero!' Error
from tblPcardGL
left outer join #tempGLsum ON
tblPcardGL.glID = #tempGLsum.glID
where tblPcardGL.glID = #glID
and (tblPcardGL.orgAmt - tblPcardGL.amt - #tempGLsum.sumAmt) < 0
Then do the update with another where clause:
update tblPcardGL
set amt =
(
select
case (select COUNT(*) as numRecs from #tempGLsum)
when 0 then
tblPcardGL.orgAmt
else
(tblPcardGL.orgAmt - #tempGLsum.sumAmt)
end
)
from tblPcardGL
left outer join #tempGLsum ON
tblPcardGL.glID = #tempGLsum.glID
where tblPcardGL.glID = #glID
and (tblPcardGL.orgAmt - tblPcardGL.amt - #tempGLsum.sumAmt) >= 0
You should consider wrapping all your #tempGLsum.sumAmt fields in isnull(#tempGLsum.sumAmt,0) because you used a left join so that column might evaluate to null, which will make any expression it is in become null.
I need a query to assign teams to a series of users. Data looks like this:
UserId Category Team
1 A null
2 A null
3 B null
4 B null
5 A null
6 B null
8 A null
9 B null
11 B null
Teams should be created by sorting by userid and the first userid becomes the team number and the consecutive A's are part of that team as are the B's that follow. The first A after the Bs starts a new team. There will always be at least one A and one B. So after the update, that data should look like this:
UserId Category Team
1 A 1
2 A 1
3 B 1
4 B 1
5 A 5
6 B 5
8 A 8
9 B 8
11 B 8
EDIT:
Need to add that the user id's will not always increment by 1. I edited the example data to show what I mean. Also, the team ID doesn't strictly have to be the id of the first user, as long as they end up grouped properly. For example, users 1 - 4 could all be on team '1', users 5 and 6 on team '2' and users 8,9 and 11 on team '3'
First you could label each row with an increasing number. Then you can use a left join to find the previous user. If the previous user has category 'B', and the current one category 'A', that means the start of a new team. The team number is then the last UserId that started a new team before the current UserId.
Using SQL Server 2008 syntax:
; with numbered as
(
select row_number() over (order by UserId) rn
, *
from Table1
)
, changes as
(
select cur.UserId
, case
when prev.Category = 'B' and cur.Category = 'A' then cur.UserId
when prev.Category is null then cur.UserId
end as Team
from numbered cur
left join
numbered prev
on cur.rn = prev.rn + 1
)
update t1
set Team = team.Team
from Table1 t1
outer apply
(
select top 1 c.Team
from changes c
where c.UserId <= t1.UserId
and c.Team is not null
order by
c.UserId desc
) as team;
Example at SQL Fiddle.
You can do this with a recursive CTE:
with userCTE as
(
select UserId
, Category
, Team = UserId
from users where UserId = 1
union all
select users.UserId
, users.Category
, Team = case when users.Category = 'A' and userCTE.Category = 'B' then users.UserId else userCTE.Team end
from userCTE
inner join users on users.UserId = userCTE.UserId + 1
)
update users
set Team = userCTE.Team
from users
inner join userCTE on users.UserId = userCTE.UserId
option (maxrecursion 0)
SQL Fiddle demo.
Edit:
You can update the CTE to get this to go:
with userOrder as
(
select *
, userRank = row_number() over (order by userId)
from users
)
, userCTE as
(
select UserId
, Category
, Team = UserId
, userRank
from userOrder where UserId = (select min(UserId) from users)
union all
select users.UserId
, users.Category
, Team = case when users.Category = 'A' and userCTE.Category = 'B' then users.UserId else userCTE.Team end
, users.userRank
from userCTE
inner join userOrder users on users.userRank = userCTE.userRank + 1
)
update users
set Team = userCTE.Team
from users
inner join userCTE on users.UserId = userCTE.UserId
option (maxrecursion 0)
SQL Fiddle demo.
Edit:
For larger datasets you'll need to add the maxrecursion query hint; I've edited the previous queries to show this. From Books Online:
Specifies the maximum number of recursions allowed for this query.
number is a nonnegative integer between 0 and 32767. When 0 is
specified, no limit is applied.
In this case I've set it to 0, i.e. not limit on recursion.
Query Hints.
I actually ended up going with the following. It finished on all 3 million+ rows in a half an hour.
declare #userid int
declare #team int
declare #category char(1)
declare #lastcategory char(1)
set #userid = 1
set #lastcategory='B'
set #team=0
while #userid is not null
begin
select #category = category from users where userid = #userid
if #category = 'A' and #lastcategory = 'B'
begin
set #team = #userid
end
update users set team = #team where userid = #userid
set #lastcategory = #category
select #userid = MIN(userid) from users where userid > #userid
End
I've run into a tricky issue with recursive searching in an eCommerce shop stored procedure. Basically this single procedure will return all products factoring in basic filters and paging, and using a parent/child category table to perform recursive checks down the hierarchy. This is works beautifully and the CTE's run extremely fast, however the recent addition of a keyword search which needs to search across the Category Name, Product Name, and Style Number has caused dramas.
This seemed quite trivial at first as the 1st CTE already generates a table of all relevant categories in the hierarchy based on the supplied #categoryid and then joins onto the rest of the Product specific tables for all filtering. The Product Name and Style Number search works fine, but I cannot for the life of me get a Category Name search to work because it needs to search the category tree for any matches down the hierarchy tree starting from the top.
EDIT: I'm now thinking it may just be a lot easier to add a "tag" table against Products which stores all keyword related tags such as category name, product name and style etc and search directly against the tags.
For example a subset of the Category hierarchy looks like this:
Mens
- Polos
- Jerseys
- Pants
Womens
- Pants
- Shirts
- Polos
Supporters
- State Of Origin
- Mens
- Womens
- Kids
- Bulldogs
- Jerserys
- Pants
- Shirts
- Caps
- Warratahs
In my sample code below i am passing a search term of "origin mens" which should return all products within the "State of Origin" category that are also within the "Mens" category. The only thing it matches on is Product Names that start with "Origin" and nothing else because the category at the product level is not "State of Origin" as this is the parent. Any help here would be fantastic!
-- Variable Declarations
DECLARE #categoryid int
DECLARE #minprice int
DECLARE #maxprice int
DECLARE #sizefilter int
DECLARE #colourfilter int
DECLARE #searchstring varchar(255)
DECLARE #totalrows int
-- Variables values for testing
SET #categoryid = 0
SET #minprice = 0
SET #maxprice = 0
SET #sizefilter = 0
SET #colourfilter = 0
SET #searchstring = 'origin mens'
-- Setup paging table
DECLARE #indextable table (rownum int identity(1,1), recordid int);
BEGIN
-- First run CTE recursively over all categories in hierarchy
;WITH categoryCTE AS (
SELECT cat.id as CategoryId, cat.name as CategoryName
FROM dbo.shopcategory AS cat
WHERE (#categoryid = 0 OR cat.id = #categoryid)
AND cat.isenabled = 1
UNION ALL
SELECT child.id as CategoryId, child.name as CategoryName
FROM dbo.ShopCategory AS child
INNER JOIN categoryCTE AS parent
ON child.parentid = parent.CategoryId
WHERE child.isenabled = 1
),
-- Now join CTE onto products tables via linker product_shopcategory
productsCTE AS (
SELECT p.id, ppc.shopcategoryid, ppc.listorder as catlistorder
FROM categoryCTE as cat
INNER JOIN product_shopcategory ppc ON ppc.shopcategoryid = cat.CategoryId
INNER JOIN product p ON ppc.productid = p.id
INNER JOIN productlocality pl ON pl.productid = p.id
-- ** SEARCH - Join List to Table function of keywords
INNER JOIN dbo.udf_parseList(#searchString, ' ') s
ON (cat.CategoryName + p.Name + p.stylenumber LIKE '%' + s.array_Value + '%')
LEFT JOIN product_quantity pq ON pq.productid = p.id AND pq.localityid = #localityid
LEFT JOIN productcolour pc ON pc.productid = p.id
LEFT JOIN productcolourswatch pcs ON pc.productcolourswatchid = pcs.id
LEFT JOIN product_productsize pps ON pps.productid = p.id
LEFT JOIN productsize ps ON pps.productsizeid = ps.id
WHERE p.isenabled = 1
AND pq.quantity > 1
AND (pc.isenabled IS NULL OR pc.isenabled = 1)
AND (#minprice = 0 OR pl.price >= #minprice)
AND (#maxprice = 0 OR pl.price <= #maxprice)
-- Colour Group Filters
AND (#colourfilter = 0
OR
(pcs.swatchgroupid = #colourfilter AND (pq.productcolourid = pc.id AND pq.quantity > 0))
)
-- Size Group Filters
AND (#sizefilter = 0
OR
(ps.sizegroupid = #sizefilter AND (pq.productsizeid = pps.productsizeid AND pq.quantity > 0))
)
)
-- Create Paging table of results and strip out duplicates with group by
INSERT INTO #indextable (recordid)
SELECT DISTINCT id
FROM productsCTE
GROUP BY id
ORDER BY id;
Finally solved it! I almost went down the path of creating a full tag table structure so that i could search directly against keyword tags rather than the direct data, however in trying to script a product tags table containing a nesting of the category hierarchy I found the solution which was quite simple.
In the solution procedure below i've created a new column in the CategoryCTE to hold a comma delimited list of category names that is built recursively and this then tracks the full tree for the supplied CategoryId. Now that i have a comma delimited list of Category names, I can then factor this into my 2nd CTE and perform a standard LIKE clause factoring in Product Name, Style Number, and Category Names. Finally in order to make this search a little smarter i made the keyword search inclusive of all keywords so that "mens origin" will only return products matching both of these keywords as oppose to any matches, and this was done using the NOT EXISTS clause.
Hope this helps someone else it performs very fast as well!
-- Variable Declarations
DECLARE #categoryid int
DECLARE #minprice int
DECLARE #maxprice int
DECLARE #sizefilter int
DECLARE #colourfilter int
DECLARE #searchstring varchar(255)
DECLARE #totalrows int
-- Variables values for testing
SET #categoryid = 0
SET #minprice = 0
SET #maxprice = 0
SET #sizefilter = 0
SET #colourfilter = 0
SET #searchstring = 'origin mens'
-- Setup paging table
DECLARE #indextable table (rownum int identity(1,1), recordid int);
BEGIN
-- First run CTE recursively over all categories in hierarchy inclusive of supplied categoryId
;WITH categoryCTE AS (
SELECT cat.id as CategoryId, cat.name as CategoryName,
CONVERT(varchar(255),cat.name) AS Tags
FROM dbo.shopcategory AS cat
WHERE (#categoryid = 0 OR cat.id = #categoryid)
AND cat.isenabled = 1
UNION ALL
SELECT child.id as CategoryId, child.name as CategoryName, CONVERT(varchar(255),
parent.Tags + CONVERT(varchar(32),',' + child.name)) AS Tags
FROM dbo.ShopCategory AS child
INNER JOIN categoryCTE AS parent
ON child.parentid = parent.CategoryId
WHERE child.isenabled = 1
),
-- Now join CTE onto products tables via linker product_shopcategory
productsCTE AS (
SELECT p.id, ppc.shopcategoryid, ppc.listorder as catlistorder
FROM categoryCTE as cat
INNER JOIN product_shopcategory ppc ON ppc.shopcategoryid = cat.CategoryId
INNER JOIN product p ON ppc.productid = p.id
INNER JOIN productlocality pl ON pl.productid = p.id
LEFT JOIN product_quantity pq ON pq.productid = p.id AND pq.localityid = #localityid
LEFT JOIN productcolour pc ON pc.productid = p.id
LEFT JOIN productcolourswatch pcs ON pc.productcolourswatchid = pcs.id
LEFT JOIN product_productsize pps ON pps.productid = p.id
LEFT JOIN productsize ps ON pps.productsizeid = ps.id
WHERE p.isenabled = 1
AND pq.quantity > 1
AND (pc.isenabled IS NULL OR pc.isenabled = 1)
AND pl.localityid = #localityid
AND (#minprice = 0 OR pl.price >= #minprice)
AND (#maxprice = 0 OR pl.price <= #maxprice)
-- Keyword Search filter
AND (#searchstring = '' OR NOT EXISTS
(
SELECT NULL
FROM dbo.udf_parseList(#searchString, ' ')
WHERE cat.Tags + p.Name + p.stylenumber + pc.stylenumber NOT LIKE '%' + array_Value + '%'
)
)
-- Colour Group Filters
AND (#colourfilter = 0
OR
(pcs.swatchgroupid = #colourfilter AND (pq.productcolourid = pc.id AND pq.quantity > 0))
)
-- Size Group Filters
AND (#sizefilter = 0
OR
(ps.sizegroupid = #sizefilter AND (pq.productsizeid = pps.productsizeid AND pq.quantity > 0))
)
)
-- Create Paging table of results and strip out duplicates with group by
INSERT INTO #indextable (recordid)
SELECT DISTINCT id
FROM productsCTE
GROUP BY id
ORDER BY id;