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
)
views:
67answers:
3
+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
2009-08-11 21:07:43
Except, pass @pc as null when you want all rows, and use this predicate: "WHERE ( @PC isnull OR Code = @PC ) "
tpdi
2009-08-11 21:24:33
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
2009-08-11 21:15:50
Warning, making this schema-bound limits your ability to change the underlying tables after the function has been created.
Adam Robinson
2009-08-11 21:22:16
@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
2009-08-11 21:43:20
+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
2009-08-11 21:20:13