0

I have the following stored procedure code working and want to add the passed parameter @tabname as a column in the result set.

CREATE PROCEDURE CountStar 
    @Tabname char(10)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL varchar(250)

    SELECT @SQL = 'SELECT ETL_LAST_UPD_DTTM, COUNT(*) FROM ls.' + QuoteName(@Tabname) +
    'GROUP BY ETL_LAST_UPD_DTTM'
    EXEC (@SQL)

    SELECT @SQL = 'SELECT ETL_LAST_UPD_DTTM, COUNT(*) FROM ci.' + QuoteName(@Tabname) +
    'GROUP BY ETL_LAST_UPD_DTTM'
    EXEC (@SQL)
    --COMMIT
END
GO

Currently this will return the last updated timestamp and the record count for the table being passed into the stored procedure for the 2 schemas identified. I want to add the @tabname to the result set as the first column followed by last updated timestamp and the record counts. This returns 2 result sets and each should look something like this for each returned result set.

Table_name      Timestamp                   rec_cnt
--------------------------------------------------
CUSTOMERS     2015-09-24 13:10:01.1770000     378

I have tried a few things but can't get the syntax correct.

Thanks for any pointers. Pat

1
  • You need a space before Group By. ' Group By...' Commented Sep 24, 2015 at 21:41

1 Answer 1

3
CREATE PROCEDURE CountStar 
    @Tabname SYSNAME    --<-- use appropriate data type for sql server objects
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL nvarchar(max);

    SELECT @SQL = N'SELECT  @Tabname AS Table_name,ETL_LAST_UPD_DTTM, COUNT(*) 
                   FROM ls.' + QuoteName(@Tabname) +
                   N' GROUP BY ETL_LAST_UPD_DTTM'
    EXEC sp_executesql @SQL
                      ,N'@Tabname SYSNAME'
                      ,@Tabname 

    SELECT @SQL = N'SELECT @Tabname AS Table_name,ETL_LAST_UPD_DTTM, COUNT(*) 
                   FROM ci.' + QuoteName(@Tabname) +
                  N' GROUP BY ETL_LAST_UPD_DTTM'
    EXEC sp_executesql @SQL
                      ,N'@Tabname SYSNAME'
                      ,@Tabname 
END
GO
Sign up to request clarification or add additional context in comments.

1 Comment

The edited version worked.. had to declare @SQL.. Thanks much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.