我试图在查询返回的值(表名)中进行搜索,以检查是否有记录,并且该记录中的某些值为空。如果是,那么我想将表的名称插入临时表。我收到一个错误:
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
如何将计数结果转换为整数?
答案 0 :(得分: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, @test=@test OUTPUT;
IF @test > 0
BEGIN
INSERT INTO #temp2 (tablename) VALUES ( @table_name);
END
SET @count = @count + 1
答案 1 :(得分:1)
不应该" SET"而不是"选择" ?
例如,改变:
select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL'
有:
SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL'
答案 2 :(得分:0)
正如我所看到的,你的问题是,$ test变量是INT,你试图为它分配TEXT值' count ...'
使用aproach如: 选择somevalue INTO myvar from mytable WHERE uid = 1;
答案 3 :(得分: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