2014-07-25 81 views
0

我試圖從查詢返回的值(表名)中檢查是否有記錄,並且該記錄中的某些值爲空。如果他們是,那麼我想要將表名插入臨時表中。我得到一個錯誤:將動態SQL查詢的COUNT結果轉換爲INT

Conversion failed when converting the varchar value 'count(*) 
FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. 

這是查詢:

DECLARE @table_name VARCHAR(150) 
    DECLARE @sql VARCHAR(1000) 
    DECLARE @test int 

    SELECT @table_name = tableName FROM #temp WHERE id = @count 

    SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 
--ERROR is below: 
select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 
    --PRINT @sql 
    -- EXEC(@sql) 
    IF @test > 0 
    BEGIN 
    INSERT INTO #temp2 (tablename) VALUES (@table_name); 
    END 
    SET @count = @count + 1 

任何想法如何計數的結果轉換爲整數?

回答

1

檢查sp_executesql您可以在其中定義輸出參數。

DECLARE @table_name VARCHAR(150) 
DECLARE @sql VARCHAR(1000) 
DECLARE @test int 

SELECT @table_name = tableName FROM #temp WHERE id = @count 

DECLARE @SQLString nvarchar(500); 
DECLARE @ParmDefinition nvarchar(500); 

SET @SQLString = N'SELECT @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 
SET @ParmDefinition = N'@test int OUTPUT'; 

EXECUTE sp_executesql @SQLString, @ParmDefinition, @[email protected] OUTPUT; 

IF @test > 0 
    BEGIN 
     INSERT INTO #temp2 (tablename) VALUES (@table_name); 
    END 
SET @count = @count + 1 
1

不應該是「SET」而不是「select」?

如改變:

select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 

爲:

SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 
+1

@test是INT。這會失敗.... –

0

依我之見,你的問題是,$測試變量是INT和您要分配給它的文本值「 count ...'

使用類似的方法: SELECT somevalue INTO myvar FROM mytable WHERE uid = 1;

0

我修剪出來沒有必要來說明如何做到這一點的東西,所以在這裏它是:

DECLARE @table_name VARCHAR(150) 
DECLARE @CountStatement NVARCHAR(1000) 
DECLARE @test int 

SELECT @table_name = tableName FROM #temp WHERE id = @count 

SET @CountStatement = 'select @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' 
EXECUTE sp_executesql @CountStatement, N'@test INT OUTPUT', @test OUTPUT; 
SELECT @test