查询函数(MSSQL)WHILE IF语句

时间:2013-05-27 13:20:09

标签: sql sql-server if-statement func

我有

SELECT 
    Table.Citizen_id AS ID,
    Citizens.Name as Name,
    Citizens.City as City  
FROM Table 
INNER JOIN Citizens   
ON Table.Citizen_id = Citizens.id
GROUP BY Table.Citizen_id, Citizens.Name,Citizens.City;

我想要创建函数Table_Citizens,它具有像Table.Citizen_id这样的输入参数,并且仅为此ID输出结果。 但是如果Table.Citizen_id = 0那么函数应输出所有ID的数据。我想知道如何执行此操作。

CREATE FUNCTION dbo.Calls_ABCs(@ABC_id AS INT) 
RETURNS TABLE 
AS 
RETURN 
    SELECT 
    Calls.ABC_id AS ID,
    ABCs.Name as Name,
    ABCs.City as City, 
    COUNT(Calls.Call_start) as Count_Calls, 
    AVG(Calls.Duration) AS AVG_Call_duration,
    MAX(Calls.Duration) AS MAX_Call_duration,
    SUM(Calls.Duration) AS SUM_Call_duration,
    SUM(Calls.Cost) AS SUM_Call_cost,
    AVG(Calls.Cost) AS AVG_Calls_Cost,
FROM Calls 
INNER JOIN ABCs   
ON Calls.ABC_id = ABCs.id WHERE (@ABC_id=0 or Calls.ABC_id = @ABC_id) and  Calls.Call_Start > '2013-03-17'  GROUP BY Calls.ABC_id, ABCs.Name,ABCs.City;

GO 

这不起作用

2 个答案:

答案 0 :(得分:2)

您的函数中的查询将如下所示:

SELECT 
    Table.Citizen_id AS ID,
    Citizens.Name as Name,
    Citizens.City as City  
FROM Table INNER JOIN
     Citizens   
     ON Table.Citizen_id = Citizens.id
where @Id = 0 or table.Citizen_id = @id
GROUP BY Table.Citizen_id, Citizens.Name,Citizens.City;

通常,这表示NULL值而不是0,因为NULL适用于所有数据类型。在那种情况下:

where @Id is NULL or table.Citizen_id = @Id

答案 1 :(得分:2)

试试这个 -

<强>查询:

CREATE FUNCTION dbo.[udf_getCitizens]
(
      @Citizen_id INT
)
RETURNS @Result TABLE (ID INT, Name VARCHAR(50), City VARCHAR(50)) 
AS
BEGIN

    INSERT INTO @Result(ID, Name, City)
    SELECT DISTINCT
          ID = t.Citizen_id
        , c.Name
        , c.City
    FROM dbo.[Table] t 
    JOIN dbo.Citizens c ON t.Citizen_id = Citizens.id 
    WHERE @Citizen_Id = 0 OR t.Citizen_id = @Citizen_id

    RETURN

END

<强> Exec的:

DECLARE @ID INT
SELECT @ID = 5

SELECT *
FROM dbo.udf_getCitizens(@ID)