2010-11-09 28 views
36

ben Exec(@sql) gelen değer elde ve @Rowcount(int) İşteDönüş değeri

atamak istediğiniz benim sorgu i doğru anlamak

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

cevap

68

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

(i muhtemelen yok)

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

('...') '. –

0

benim prosedür olduğunu

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 = '[email protected]+' and '[email protected]+')' 
    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 
Eğer geçici bir tablo kullanabilirsiniz Öte yandan

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

: Eğer sp_executesql kullanabilirsiniz Bir yandan 0

0

bu bugünden ile oynarken oldu ... Ben de yapabilirsiniz inanmak Bu gibi @@ ROWCOUNT kullanın:

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

Sonra değiştirmek sayımı olmadan gerçek seçme ile '1 BİRLİĞİ SEÇ 2 SEÇ'. Sadece bu gibi, seçme içinde 1 koyarak öneririm:

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

yardımcı

Umut (SEÇ * koyarak aksine).

-2

ilan @nReturn int = 0 EXEC @nReturn = EXEC `değişken çağrısı içinde kapsamı dışında olacak saklı prosedürler

+1

Bu, saklı yordamın dönüş değerini almak için çalışır, ancak dinamik SQL değil. –