sql - How to use table as variable in stored procedure -


there query keep using on , over:

select column_name, count(column_name) table_name group column_name order count(column_name) desc 

i use check different values there in column , how occur. because use query , it's repeating same 4 times: column_name, like: why not make stored procedure:

create procedure countcv @table_name varchar(50),@column_name varchar(50) begin   select @column_name,count(@column_name) @table_name group @column_name order count(@column_name) end 

here stuck, can not manage variable tablename:

must declare table variable "@table_name"

there no way directly. need use dynamicsql approach. assuming pass correct table , column names. below 1 should work.

create procedure countcv @table_name varchar(50),@column_name varchar(50) begin declare @sql nvarchar(max)   set @sql  = 'select '+@column_name+',count('+@column_name+')               '+@table_name+'                group '+@column_name+'               order count('+@column_name+')'  exec sp_executesql @sql end 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -