February 14, 2006 at 9:36 am
Hi,
Can I construct and execute a dynamic statement inside a user-defined function? I dont want any resultset, just the count of rows returned, like 'SELECT COUNT(*) FROM table1'. I want to take this count and do something else.
Is this allowed in UDFs. I was not able to use GETDATE() inside the function, I didn't know everything has to be deterministic. If not, can any one suggest any other workaround.
Thanks.
February 14, 2006 at 9:49 am
No, you cannot use dynamic sql inside of a function.
February 14, 2006 at 10:44 am
If all you want is a rowcount and you are prepared to put up with an estimate then set up your function to pass in the name of your table then do something like
SELECT MAX(RowCnt) FROM Sysindexes where Id = Object_Id(@ParamTableName) AND IndId<2
February 14, 2006 at 10:54 am
No, its not just a row count. The dynamic sql has some where conditions 'SELECT COUNT(*) FROM table1 WHERE...'
May be I can execute the sql and pass the count as a parameter to the function. Can any one tell me how to get the scalar value that will be returned by this sql. I tried something like this, but it is throwing some error.
DECLARE @count INT
EXECUTE @count = ('select count(*) from table1')
SELECT @count
This is the error message Line 2: Incorrect syntax near '('. So I tried this
DECLARE @count INT
SET @count = EXECUTE ('select count(*) from table1')
SELECT @count
This is the error message Incorrect syntax near the keyword 'EXECUTE'
Thanks.
February 14, 2006 at 2:10 pm
Works great. Thanks.
February 14, 2006 at 2:11 pm
What you suppose to put in WHERE clause if you don't know which table you are querying?
_____________
Code for TallyGenerator
February 14, 2006 at 2:21 pm
The table is always the same, I know which table to query. Only the where clause changes based on some parameters.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply