I have the following SQL statement that I have been building up, which returns a range of values based on the order of values within a table for 'product data'
For example a product, TV, has a screen size and we want to query on TVs that have a screen between a specified range based on user configuration. So they may say, give me alternative TVs 3 sizes either side of 42".
This query does just that based on a specified product:
DECLARE @ProductType INT = (
SELECT p.prod_ptype_id
FROM product p
WHERE p.prod_id = @ProductId
)
DECLARE @AttributeId INT = (
SELECT at.aptype_attr_id
FROM Attribute_ProductType at
INNER JOIN Attribute a
ON a.attr_id = at.aptype_attr_id
WHERE ISNULL(a.ReplacementTolerant, 0) = 1
AND at.aptype_ptype_id = @ProductType
)
DECLARE @ToleranceRange INT = (
SELECT a.ToleranceRange
FROM Attribute_ProductType at
INNER JOIN Attribute a
ON a.attr_id = at.aptype_attr_id
WHERE ISNULL(a.ReplacementTolerant, 0) = 1
AND at.aptype_ptype_id = @ProductType
)
DECLARE @AttributeValueIndex INT = (
SELECT DISTINCT ( av.attrval_index )
FROM Product_Attribute pa
INNER JOIN AttributeValue av
ON av.attrval_attr_id = pa.pattr_attr_id
WHERE av.attrval_id = (
SELECT pattr_attrval_id
FROM product_attribute pa3
WHERE pa3.pattr_prod_id = @ProductId
AND pa3.pattr_attr_id = @AttributeId
)
);
WITH ProductTypeAttributes
AS (
SELECT DISTINCT attrval_val
,attrval_index
,ROW_NUMBER() OVER ( ORDER BY attrval_index ) AS RowNumber
FROM Product_Attribute pa
INNER JOIN AttributeValue av
ON av.attrval_id = pa.pattr_attrval_id
INNER JOIN Product p
ON p.prod_id = pa.pattr_prod_id
WHERE pa.pattr_attr_id = @AttributeId
AND p.prod_ptype_id = @ProductType
GROUP BY attrval_val
,attrval_index
)
SELECT *
FROM ProductTypeAttributes
WHERE RowNumber >= (
(SELECT DISTINCT ( RowNumber )
FROM ProductTypeAttributes pta2
WHERE attrval_index = @AttributeValueIndex)
) - @ToleranceRange
AND ( RowNumber <= (
SELECT DISTINCT ( RowNumber )
FROM ProductTypeAttributes pta3
WHERE attrval_index = @AttributeValueIndex
) + @ToleranceRange )
This is all well and good, and works exactly as I need it to albeit it may need some optimizing, but for now I just want to be able to bolt it in where it's needed as a POC.
The obvious choice is to make this a table function - but I'm at a loss on what syntax to apply when I have these 'declare' statements.
I've had a look on MSDN and at the samples which show similar samples to what I think I need to achieve, but I can't fathom out how to use the declare statements in conjunction with a table function in this manner.
Can anyone please shed any light on this?
Thanks!