I need to pass a table name and id to a function and return a row count
I need to use EXEC or SP_EXECUTESQL to run dynamic SQL
It dont work in functions. Following is my function
I need to use EXEC or SP_EXECUTESQL to run dynamic SQL
It dont work in functions. Following is my function
alter FUNCTION [dbo].[GetRowCount] (@TblName NVARCHAR(25) , @Itemid INT)
RETURNS INT
AS BEGIN
DECLARE @RowCnt INT
set @RowCnt = 0
DECLARE @Sqlstring nvarchar(2000)
set @Sqlstring = 'SELECT @RowCnt = COUNT(*) FROM ['+ @TblName +'] WHERE Itemid = '+ convert(varchar(10),@Itemid)
EXEC @Sqlstring
RETURN @RowCnt
END
"Only functions and extended stored procedures can be executed from within a function." and "Incorrect syntax near the keyword 'EXEC' "
does anyone have any ideas of a way round this ?
Thanks.
Vidhya
DavidPosted Nov 23, 2006, 9:02 AM
There are two problems with your code. One as you mentioned is to do with restrictions with what you can do inside a function. Exec'ing sql isn't allowed. So you have to use a sproc.
PROC dbo.spRowCount(@tblName nvarchar(1000), @intRowCount int OUTPUT)2ndly, when you exec sql, it is quite tricky to get information back out again. You can't just declare a variable before you exec and then use it in the exec.
The code below should give you the results your looking for (but it seems to me that this can be obtained by other means - I'll post again if I remember how.)
CREATE
AS
DECLARE
@RowCnt intDECLARE
@ExecString nvarchar(1000)SELECT
@ExecString='select @i=count(*) from ' + @tblNameSELECT
@ExecStringexec
sp_executesql @ExecString,N'@i int output', @RowCnt outputSELECT
@RowCntSET
@intRowCount=@RowCntGO
DECLARE
@intResult intexec
dbo.spRowCount N'tblNonMFTShareclassDetails',@intResult outputSELECT
@intResult