sp_executesql
与group by
子句不能正常工作,我正在调试这个
我从sp_executesql
中剥离了所有参数,并有这个简单的批处理:
declare @SQLStatement nvarchar(1000);
set @SQLStatement='select '+cast(count('phonenumbertypeid') as nvarchar(100))+ ' from person.personphone
group by phonenumbertypeid'
exec sp_executesql @SQLStatement
现在,这给了我1
的结果,这肯定是错误的。
我在没有sp_executesql
的情况下运行了相同的语句,它给了我736
的正确结果,这是正确的:
select cast(COUNT(PhoneNumberTypeID) as nvarchar(100)) from person.PersonPhone
group by PhoneNumberTypeID
我坚信这个问题是由我在@SQLStatement
中表演的演员引起的:
set @SQLStatement='select '+cast(count('phonenumbertypeid') as nvarchar(100))+ ' from person.personphone
在sp_executesql
语句中,我如何解决我与group by
子句的问题?
如果执行此命令,您将看到问题:
declare @SQLStatement nvarchar(1000);
set @SQLStatement='select '+cast(count('phonenumbertypeid') as nvarchar(100))+ ' from person.personphone
group by phonenumbertypeid'
select @SQLStatement
你正在执行这个:
select 1 from person.personphone group by phonenumbertypeid
试试这个(未测试):
declare @SQLStatement nvarchar(1000);
set @SQLStatement='select cast(count(''phonenumbertypeid'') as nvarchar(100)) from person.personphone
group by phonenumbertypeid'
exec sp_executesql @SQLStatement