将varchar值'SELECT'转换为数据类型tinyint时转换失败

时间:2013-03-25 08:52:01

标签: sql sql-server-2008-r2

我正在尝试获取特定行的列的值,但我收到了以下错误。我不知道是什么问题。这是我的SQL查询:

declare @Service_Table varchar(30),
        @Ser_Id tinyint,
        @sql  nvarchar(100), 
        @Service_State tinyint

SET @Service_Table='Third_Party_Assistance'
set @Ser_Id = 2
SET @sql = 'SELECT ' + @Service_State + '=  Service_State_Id FROM dbo.' + 
          quotename(@Service_Table) + ' WHERE Service_Id = ' + 
          convert(varchar,@Ser_Id) + 'AND Service_State_Id <> 4'
EXEC sp_executesql @sql

3 个答案:

答案 0 :(得分:1)

您没有为@Service_State变量分配任何值!!

答案 1 :(得分:1)

sp_executesql系统存储过程与OUTPUT参数

一起使用
declare @Service_Table varchar(30),
        @Ser_Id tinyint,
        @sql  nvarchar(4000), 
        @Service_State tinyint

SET @Service_Table='Third_Party_Assistance'
SET @Ser_Id = 2
SET @sql = 'SELECT @Service_State =  Service_State_Id FROM dbo.' + 
            quotename(@Service_Table) + ' WHERE Service_Id = ' +
            '@Ser_Id AND Service_State_Id <> 4'
EXEC sp_executesql @sql, N'@Ser_Id tinyint, @Service_State tinyint OUTPUT', @Ser_Id, @Service_State OUTPUT
SELECT @Service_State

答案 2 :(得分:0)

你还没有问过这个问题吗? 声明在哪里?

尝试投射@Service_State:cast(@Service_State) as varchar(255))

declare @Service_Table varchar(30),
        @Ser_Id tinyint,
        @sql  nvarchar(30), 
        @Service_State tinyint

SET @Service_Table='Third_Party_Assistance'
set @Ser_Id = 2
SET @sql = 'SELECT ' + cast(@Service_State as varchar(255))+ '=  Service_State_Id FROM dbo.' + 
          quotename(@Service_Table) + ' WHERE Service_Id = ' + 
          convert(varchar,@Ser_Id) + 'AND Service_State_Id <> 4)'