Search code examples
sql-serverrowcountraiserror

return @@rowcount result on SQL query


I wanted to raiserror if exists and then print the number of rows that are matching .But this doesnt work . Please help .

if exists (select * from [rto] a
     inner join rt b
     on a.NUM=b.TABLE_NAME
     where a.START_YEAR between b.YEAR_START and b.YEAR_STOP)
     Raiserror ('Matched recs found',16,1)
     print 'There are' +  cast(@@rowcount as varchar(20)) + 'matched rows'

Solution

  • This is an alternative to your original post...not sure if you have specific requirements, but this should get you the error output that you desire:

    DECLARE @rowcount INT
    SET @rowcount = (select COUNT(*) from [rto] a
        inner join rt b
        on a.NUM=b.TABLE_NAME
        where a.START_YEAR between b.YEAR_START and b.YEAR_STOP)
    IF @rowcount > 0
    BEGIN
        Raiserror ('Matched recs found',16,1)
        print 'There are ' +  cast(@rowcount as varchar(20)) + ' matched rows'
    END