Sql server EXEC语句中的类型转换
假设我们有以下声明:Sql server EXEC语句中的类型转换,sql-server,tsql,type-conversion,implicit-conversion,Sql Server,Tsql,Type Conversion,Implicit Conversion,假设我们有以下声明: declare @a int; set @a = 1; 还需要生成一些信息性消息,例如: select 'the value of @a is ' + @a; 上述语句将生成错误,因为需要进行类型转换,正确的方法是: select 'the value of @a is ' + convert(varchar(10), @a); 然后,如果同样的事情需要动态完成,那么可以预期以下内容应该是正确的: exec('select ''the value of @a is '
declare @a int;
set @a = 1;
还需要生成一些信息性消息,例如:
select 'the value of @a is ' + @a;
上述语句将生成错误,因为需要进行类型转换,正确的方法是:
select 'the value of @a is ' + convert(varchar(10), @a);
然后,如果同样的事情需要动态完成,那么可以预期以下内容应该是正确的:
exec('select ''the value of @a is ' + convert(varchar(10), @a) + '''');
令人惊讶的是,事实并非如此,并且会产生语法错误。与select
语句相反,在这种情况下正确的方法是:
exec('select ''the value of @a is ' + @a + '''');
所以问题是,为什么在
select
语句中需要进行类型转换,而在exec(string)
语句中则不合法?在运行任何DML语句时,都检查了语法。正如我们所知,Exec不是DML语句,它提供SQL环境来运行任何脚本。
在执行隐式转换的exec中,exec('select'@a的值为'+@a++'')。
在这种情况下。
exec('select'@a的值为'+convert(varchar(10),@a)+'');
您正在使用convert函数,该函数用于DML操作及其在exec之前检查语法
declare @a int,@str varchar(8000)=''
set @a = 124586;
select @str='select ''the value of @a is ' + convert(varchar(10), @a) + ''''
exec( 'select ''the value of @a is ' + @a + '''')
exec(@str);