Return value from exec(@sql)

SqlSql ServerSql Server-2005Tsql

Sql Problem Overview


I want get the value from Exec(@sql) and assign to @Rowcount(int)

Here is my query:

'SET @RowCount = (select count(*) 
                    FROM dbo.Comm_Services 
                   WHERE CompanyId = '+cast(@CompanyId as char)+' and '+@condition+')'

Sql Solutions


Solution 1 - Sql

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

Solution 2 - Sql

DECLARE @nReturn int = 0
EXEC @nReturn = Stored Procedure

Solution 3 - Sql

that's my procedure

CREATE PROC sp_count
    @CompanyId sysname,
    @codition sysname
    AS
    SET NOCOUNT ON
    CREATE TABLE #ctr
    ( NumRows int )
    
    DECLARE @intCount int
         , @vcSQL varchar(255)
    
    SELECT    @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services 
                       WHERE CompanyId = '+@CompanyId+' and '+@condition+')'
    EXEC      (@vcSQL)
    
    IF @@ERROR = 0
    BEGIN
         SELECT    @intCount = NumRows
         FROM #ctr
    
         DROP TABLE #ctr
         RETURN @intCount
    END
    ELSE
    BEGIN
         DROP TABLE #ctr
         RETURN -1
    END
    GO

Solution 4 - Sql

Was playing with this today... I believe you can also use @@ROWCOUNT, like this:

DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount

Then replace the SELECT 1 UNION SELECT 2 with your actual select without the count. I'd suggest just putting 1 in your select, like this:

SELECT 1
FROM dbo.Comm_Services
WHERE....
....

(as opposed to putting SELECT *)

Hope that helps.

Solution 5 - Sql

If i understand you correctly, (i probably don't)

'SELECT @RowCount = COUNT(*)
                   FROM dbo.Comm_Services
                   WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
                   AND ' + @condition

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsreekanth View Question on Stackoverflow
Solution 1 - SqlManfred SorgView Answer on Stackoverflow
Solution 2 - SqlbugstarView Answer on Stackoverflow
Solution 3 - SqlkstView Answer on Stackoverflow
Solution 4 - SqlTylerMView Answer on Stackoverflow
Solution 5 - SqlRPM1984View Answer on Stackoverflow