I currently have a query in TSQL that takes in a collection of product IDs and associated prices and calculates discounted pricing. At the moment, the product IDs and initial pricing are in the database, and the query I've written joins against those items. The query sets pricing based on other products that have come before it in the query, so I can't use individual queries for the price of product one, then product two, etc. They have to be evaluated as a collection together.
I now have to refactor this discount logic into a table-valued UDF that will be used in two ways:
- The existing approach, where it will need to perform discount pricing against a collection of IDs and pricing that existing in the DB.
- A new approach where I will need to pass the IDs and initial pricing into the UDF from PHP (they won't exist in the DB).
My problems for each respective point are:
- I essentially need to pass a table into the UDF. From what I've read, that means I need to create my own user-defined table type, query my product IDs/pricing in the database into that table type, and then pass as an argument to the UDF. Is that correct?
- The new approach is where I'm really lost, as I'm not sure how to take what is basically an array of ID/price pairs in PHP (think shopping cart) and pass that to my UDF to get the resulting pricing. I could manually hack together a query that generates my user-defined table my from multiple one-line statements and
UNION
them together, but otherwise have no idea how to pass multiple 'rows' from PHP to a UDF.
What is the correct way of handling this?
Full credit to https://forums.whirlpool.net.au/forum-replies.cfm?t=2598049
Define a "User Defined Table Type" that defines the table structure to pass to the UDF, eg CREATE TYPE [PRODUCTIDPRICING] AS TABLE( PRODUCTID INT, PRODUCTPRICE NUMERIC(18,2) ) When wanting to update your pricing, your TSQL will do the following:
DECLARE @PRODUCTSTODISCOUNT PRODUCTIDPRICING;
insert into @PRODUCTSTODISCOUNT values (1,1.23)
@PRODUCTSTODISCOUNT
variable