sp_ExecuteSQL in User Defined Function This is driving me crazy.
I need to create a UDF that would return a TRUE/FALSE (bit) value based
on a comparison it does.
CREATE FUNCTION dbo.SelectedByApplication
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int
)
RETURNS BIT AS
BEGIN
DECLARE @SQL NVARCHAR(1000)
DECLARE @Param NVARCHAR(500)
DECLARE @Result int
SET @SQL = N'SELECT @result = COUNT(*) FROM [' + @TableToCheck + '] '
+
'WHERE [' + @ColumnToCompare + '] = @ValueInTable AND
ApplicationID = @ApplicationID'
SET @Param = N'@result int out, @ValueInTable int, @ApplicationID
int'
EXECUTE sp_executesql @SQL, @Param, @result out, @ValueInTable,
@ApplicationID
if @result > 0
return 1
return 0
END
All I need the function to do is fill in a column based on whether
there is a relation between a list of data and the item. I'm trying to
use it in the following query:
SELECT *, EXEC dbo.SelectedByApplication(4, 'IPM_Application_DataType',
'DataTypeID', DataTypeID)
FROM IPM_DataType DT
The idea is to make this call and then be able to populate a list of
checkboxes based on the information it returns. It should return
something similiar to:
Column1 Column2 UDFColumn
1 SomeValue 0
2 OtherValue 1
3 DifferentValue 0
4 LastValue 1
After reading some of the posts and discovering you can't execute
dynamic SQL in a UDF I decided to split the function into a function
and stored procedure:
CREATE FUNCTION dbo.SelectedByApplication
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int
)
RETURNS BIT AS
BEGIN
Declare @Result INT
EXEC DynamicCompare @ApplicationID, @TableToCheck, @ColumnToCompare,
@ValueInTable, @Result
if(@Result > 0)
return 1
return 0
END
CREATE PROCEDURE dbo.DynamicCompare
(
@ApplicationID int,
@TableToCheck nvarchar(50),
@ColumnToCompare nvarchar(50),
@ValueInTable int,
@Result int out
)
AS
DECLARE @SQL NVARCHAR(1000)
DECLARE @Param NVARCHAR(500)
SET @SQL = N'SELECT @result = COUNT(*) FROM [' + @TableToCheck + ']
' +
'WHERE [' + @ColumnToCompare + '] = @ValueInTable AND
ApplicationID = @ApplicationID'
SET @Param = N'@result int out, @ValueInTable int, @ApplicationID
int'
EXECUTE sp_executesql @SQL, @Param, @result out, @ValueInTable,
@ApplicationID
I get the same error message about only being able to execute functions
and extended stored procedures in a user defined function.
Does anyone have any ideas as to how I can dynamically execute this
query? The reason I say dynamic is I need this same comparison for
about 25 different tables. Thanks! |