SQL Server Where has this T-SQL code gone wrong. Not getting count as expected

hpxqektj  于 2023-05-05  发布在  Go
关注(0)|答案(1)|浏览(213)
go
declare @sch_names varchar(50), @table_names varchar(50), @rwcounting int
set @sch_names='HumanResources'
set @table_names ='Employee'
set @rwcounting = 0
declare @fetchsql nvarchar(max)
set @fetchsql += 'select @rwcounting = count(1) as "countnum" from '+@sch_names+'.'+@table_names
exec(@fetchsql)
select @rwcounting

I am not getting the count from the table. Getting the count as zero. but expected count was 290.

dxxyhpgq

dxxyhpgq1#

Your code had three mistakes

1.review this code because you can't concatenate null with string

set @fetchsql =

2.you must remove "as "countnum""

3.you must use sp_executesql for return ouput

this is correct

go
declare @sch_names varchar(50), @table_names varchar(50), @rwcounting int=0
set @sch_names='HumanResources'
set @table_names ='Employee'
set @rwcounting = 0
declare @fetchsql nvarchar(max)=''
set @fetchsql += 'select @rwcounting = count(1)  from ' + quotename(@sch_names) + '.' + quotename(@table_names)

exec sp_executesql @fetchsql, N'@rwcounting int output', @rwcounting output

select @rwcounting

相关问题