views:

67

answers:

3
CREATE FUNCTION GetPayCodeList
(     
     -- Add the parameters for the function here
      @PC varchar(50)
)

RETURNS TABLE 
AS
RETURN 
(     IF @PC = '*'
       SELECT DISTINCT ID, Code, Description
                            FROM   tbl
      ELSE
             SELECT DISTINCT ID, Code, Description
                            FROM   tbl
          WHERE Code = @PC
)
+2  A: 

Are any of those columns character and DISTINCT?

As a side note, you could rewrite it as this to make it simpler:

SELECT DISTINCT ID, Code, Description
    FROM   tbl
    WHERE @PC = '*' OR Code = @PC
lavinio
Except, pass @pc as null when you want all rows, and use this predicate: "WHERE ( @PC isnull OR Code = @PC ) "
tpdi
A: 

Try this:

CREATE FUNCTION GetPayCodeList(          -- Add the parameters for the function here      
@PC varchar(50))
RETURNS @tbl TABLE (
    ID int
    , Code varchar(50)
    , Description varchar(max))
WITH SCHEMABINDING  
AS
BEGIN
IF @PC = '*'      
    SELECT DISTINCT ID, Code, Description                            
    FROM   tbl      
ELSE             
    SELECT DISTINCT ID, Code, Description                            
    FROM   tbl          
    WHERE Code = @PC
END
Remus Rusanu
Warning, making this schema-bound limits your ability to change the underlying tables after the function has been created.
Adam Robinson
@Adam: on the other hand *not* marking it schemaboudn will make it perform dismally: http://blogs.msdn.com/sqlprogrammability/archive/2006/05/12/596424.aspx
Remus Rusanu
+1  A: 

You will have to write a multi-step function, you cannot do that an inline function.

CREATE FUNCTION GetPayCodeList
(     
     -- Add the parameters for the function here
      @PC varchar(50)
)

RETURNS @table TABLE (ID int NOT NULL,
... //others fields ) AS
BEGIN
IF @PC = '*'
INSERT @table (SELECT DISTINCT ID, Code, Description
                        FROM   tbl) FROM tbl
ELSE
INSERT @table ( SELECT DISTINCT ID, Code, Description
                        FROM   tbl
      WHERE Code = @PC) FROM tbl
RETURN @table
END
RRUZ