SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Dynamic Function to return number of rec in table
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

aakcse
Aged Yak Warrior

India
570 Posts

Posted - 08/05/2014 :  00:53:01  Show Profile  Reply with Quote
I want to write a function, which accept 3 parameters, 1 TableName 2 ColumnName 3 DateValue,
and returns number of records in that table for that particular date(in parameter date),
I have written below function but it is not returning the desired result, can anyone help me.


CREATE FUNCTION dbo.[f_Rec_cnt] 
	(@InTableName NVARCHAR(100),
	 @InDtColName NVARCHAR(50),
	 @InDate NVARCHAR(50)
        )
RETURNS INT
AS
BEGIN
DECLARE @vRowCnt NVARCHAR(50)
DECLARE @vTableName NVARCHAR(150)
DECLARE @vDtColName NVARCHAR(50)
DECLARE @vInDate NVARCHAR(50)
DECLARE @vSql NVARCHAR(500)
SELECT @vTableName=@InTableName,@vDtColName=@InDtColName,@vInDate=@InDate
      SELECT @vInDate=''''+CAST(@InDate AS NVARCHAR)+''''
      SELECT @vSql='SELECT @vRowCnt = COUNT(*) FROM '+@vTableName+' WHERE '+@vDtColName+'='+@vInDate
      EXECUTE SP_EXECUTESQL @vSql
      RETURN (CAST(@vRowCnt AS INT))
END


-Neil

aakcse
Aged Yak Warrior

India
570 Posts

Posted - 08/05/2014 :  01:11:04  Show Profile  Reply with Quote
Came to know that function cannot have dynamic sql as above, then converted to SP but still getting the result as NULL in the output parameter?


ALTER PROCEDURE [p_Rec_cnt] 
			   (
					@InTableName NVARCHAR(100),
					@InDtColName NVARCHAR(50),
					@InDate NVARCHAR(50),
					@InRowCnt  INT OUTPUT
			   )
AS
BEGIN
DECLARE @vRowCnt NVARCHAR(50)
DECLARE @vTableName NVARCHAR(150)
DECLARE @vDtColName NVARCHAR(50)
DECLARE @vInDate NVARCHAR(50)
DECLARE @vSql NVARCHAR(500)
      SELECT @vTableName=@InTableName,@vDtColName=@InDtColName,@vInDate=@InDate
      SELECT @vInDate=''''+CAST(@InDate AS NVARCHAR)+''''
      SELECT @vSql='SELECT '+@vRowCnt+' = COUNT(*) FROM '+@vTableName+' WHERE '+@vDtColName+'='+@vInDate
      EXECUTE SP_EXECUTESQL @vSql
      SELECT  @InRowCnt = @vRowCnt
END


-Neil
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000