SQL Server Return value from exec(@sql)

8yoxcaq7  于 2023-03-07  发布在  其他
关注(0)|答案(6)|浏览(135)

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+')'
bsxbgnwa

bsxbgnwa1#

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);
s6fujrry

s6fujrry2#

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

5gfr0r5j3#

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.

b1zrtrql

b1zrtrql4#

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
klsxnrf1

klsxnrf15#

With this pattern, you can return whatever type or results you are after from the results of your exec statement.

declare @result table ([rowcount] int);

insert into @result ([rowcount])
Exec(@sql)
wa7juj8i

wa7juj8i6#

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

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

相关问题