T-SQL表值函数中的多个案例

时间:2016-01-26 22:31:13

标签: sql sql-server tsql

我需要创建用户定义的函数,该函数返回来自库存的特定产品的所有值。它应该是这样的:

 Select * from Task10('PC',100,500) 
此外,所有数据都在不同的表格中,我不知道如何在没有IF语句的情况下执行此操作。用户定义返回TABLE的函数的另一个困难需要以Select开头。此代码段对我不起作用。


USE MyDataBase
GO
if OBJECT_ID ('Task10','FN') IS NOT NULL DROP FUNCTION Task10;
GO
Create function Task10 (@type_product VARCHAR(10),@min_price FLOAT, @max_price FLOAT)
RETURNS TABLE
AS RETURN(
Select *, case @type_product
when 'PC' then (products.Model = pc_uri.Model AND products.type='PC' AND pc_uri.value>@min_price and pc_uri.value<@max_price)
when 'Laptops' then (products.Model=laptop_uri.Model AND products.type='Laptops' AND laptop_uri.value>@min_price and laptop_uri.value<@max_price)
when 'Printers' then (products.Model=Printers.Model AND products.type='Printers' AND Printers.value>@min_price and Printers.value<@max_price)
from case @type_product
when 'PC' pc_uri,products
when 'Laptops' laptop_uri,products
when 'Printers' Printers,products
)
这个有效,但不会返回所有属性,只有两个。

USE MyDataBase
GO
if OBJECT_ID ('Task10','FN') IS NOT NULL DROP FUNCTION Task10;
GO
Create function Task10 (@type_product VARCHAR(10),@min_price FLOAT, @max_price FLOAT)
RETURNS TABLE
AS RETURN(
Select distinct product.Model,product.Type from product,laptops,printers,pc_uri
      where (
         (@type_product = 'PC' AND product.Model=pc_uri.Model AND product.Type='PC' AND pc_uri.value>@min_price and pc_uri.value<@max_price)
      OR (@type_product = 'printers' AND product.Model=printers.Model AND product.Type='printers' AND printers.value>@min_price and printers.value<@max_price)
      OR (@type_product = 'Laptop-uri' AND product.Model=laptops.Model AND product.Type='Laptop-uri' AND laptops.pret>@min_price and laptops.value<@max_price)
      )
)

1 个答案:

答案 0 :(得分:1)

试试这个..使用左连接,你可以匹配所有东西,但让产品类型决定从哪里获得价值。

Create function Task10 (@type_product VARCHAR(10),@min_price FLOAT, @max_price FLOAT)
    RETURNS TABLE
    AS RETURN(
    Select products.*, case @type_product
    when 'PC' then pc_uri.value
    when 'Laptops' then laptop_uri.value
    when 'Printers' then Printers.value
      else 0 end price
    from products
      left join pc_uri on pc_uri.Model = products.Model and (pc_uri.value>@min_price and pc_uri.value<@max_price)
      left join laptop_uri on laptop_uri.Model = products.Model AND (laptop_uri.value>@min_price and laptop_uri.value<@max_price)
      left join Printers on Printers.Model = products.Model and (Printers.value>@min_price and Printers.value<@max_price)