I could really use some help writing a multi-statement table-valued function that uses the following logic:
- Accepts a varchar parameter as input
- If the parameter starts with A, run a select statement
- If no rows are returned, run a select statement
- If the parameter does not start with A, run a select statement
- If no rows are returned, run a select statement
- Returns an output table, which will be one of the result-sets from above depending on the parameter
So far, this is what I have:
CREATE FUNCTION dbo.CheckAccess
(@UserName varchar(30))
RETURNS @AccessTable TABLE (User varchar(max), Access varchar(max))
AS
BEGIN
IF LEFT(@UserName,1) = 'A'
INSERT INTO @AccessTable
SELECT
CASE
WHEN EXISTS (SELECT User, Access FROM dbo.AccessTable1 WHERE User = @UserName)
THEN (SELECT User, Access FROM dbo.AccessTable1 WHERE User = @UserName)
ELSE (SELECT @UserName User, 'No Access' Access)
END
ELSE
INSERT INTO @AccessTable
SELECT
CASE
WHEN EXISTS (SELECT User, Access FROM dbo.AccessTable2 WHERE User = @UserName)
THEN (SELECT User, Access FROM dbo.AccessTable2 WHERE User = @UserName)
ELSE (SELECT @UserName User, 'No Access' Access)
END
RETURN
END;
Not sure what I'm missing here, but I'm receiving the errors below:
Msg 116, Level 16, State 1, Procedure CheckAccess, Line 90
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Procedure CheckAccess, Line 92
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 213, Level 16, State 1, Procedure CheckAccess, Line 11
Column name or number of supplied values does not match table definition.
I know how to do this fairly easily in a stored procedure, using temp tables, but since they are not an option in functions, I'm having a bit of difficulty. If anyone can offer some suggestions, I'd really appreciate it. Thanks in advance.