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+')'
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);
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
Was playing with this today... I beleive 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.
declare @nReturn int = 0
EXEC @nReturn = Stored Procedures
If i understand you correctly, (i probably don't)
'SELECT @RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
AND ' + @condition