Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server passing table columns to a function's parameter

I have an SQL function which returns the minimum and maximum selling price of an item. I'd like to make a query which gets other StockItem columns together with it's selling price

like so:

SELECT i.StockItemID ii, 
       i.Name, 
       i.Code, 
       pli.SellingPrice AS MinSellingPrice,
       pli.StandardSellingPrice AS MaxSellingPrice,
       i.WebDetailedDescription,
       i.WebAdditionalInfo,
       i.FeaturedItemDescription
FROM SC_StockItem AS i, 
     func_GetPrice(17, i.StockItemID, 5) pli

However this gives an error:

Msg 4104, Level 16, State 1, Line 12 The multi-part identifier "i.StockItemID" could not be bound.

any idea how I can do this ?

Thanks in advance

like image 244
Jonny Avatar asked Jan 11 '13 14:01

Jonny


People also ask

How do you pass a list of values to a parameter of a stored procedure?

CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.

Can I pass a table as a parameter in SQL?

You can declare table-valued variables within dynamic Transact-SQL statements and pass these variables as table-valued parameters to stored procedures and functions.

Can we pass dynamic parameters in SQL query?

Dynamic SQL queries are those built at runtime based on one or more variable values. To execute those queries, we must concatenate them into one SQL statement and pass them as a parameter to the sp_executesql stored procedure.

Can we pass temp table as parameter to function in SQL Server?

A TEMP Table of User Defined Table Type has to be created of the same schema as that of the Table Valued parameter and then it is passed as Parameter to the Stored Procedure in SQL Server.


1 Answers

If that is a table valued function, then you can use OUTER APPLY:

select i.StockItemID ii, 
  i.Name, 
  i.Code, 
  pli.SellingPrice as MinSellingPrice, 
  pli.StandardSellingPrice as MaxSellingPrice,
  i.WebDetailedDescription, 
  i.WebAdditionalInfo, 
  i.FeaturedItemDescription
from SC_StockItem as i
OUTER APPLY func_GetPrice(17, i.StockItemID, 5) pli

From MSDN:

The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query.

like image 57
Taryn Avatar answered Nov 04 '22 10:11

Taryn