0

我有

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 

那行不通

4

2 回答 2

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
于 2013-05-27T13:21:59.850 回答
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

执行:

DECLARE @ID INT
SELECT @ID = 5

SELECT *
FROM dbo.udf_getCitizens(@ID)
于 2013-05-27T13:27:06.977 回答