Hi, I have run the following script but only columns name is showing in the result. I also want to show the rows if possible. Please help.
USE tempdb
create table travel (tr_id numeric, tr_site char(14), tr_city char(10))
insert into travel values (1,'STY_YTRY','Markham')
insert into travel values (2,'STY_YTRY_DT','Dehli')
insert into travel values (3,'STY_YTRY','NewYork')
insert into travel values (4,'STY_YTRY_HT','Emsterdam')
insert into travel values (5,'STY_YTRY','Toronto')
insert into travel values (6,'STY_YTRY','Markham')
create table travel_2 (tr_id numeric, tr_site char(10), tr_city char(8))
declare @Stablename varchar(400) = 'travel',@Dtablename varchar(400) = 'travel_2'
declare @sql varchar(max)=' Print ''Columns that has data greater that max_length are:'''+char(13)
select @sql =@sql + 'If Exists (select top 1 '+a.name+' from '+@Stablename+' where datalength('+a.name+') > '+convert(varchar,a.max_length)+') Print '''+a.name+'''' +char(13) from sys.columns a inner join sys.types b
on a.user_type_id = b.user_type_id
where object_id=object_id(@Dtablename) and b.name like '%char%'
--print @sql
Exec (@sql)
--Results from this script
Columns that has data greater that max_length are:
tr_site
tr_city
--Desired output as mentioned above
tr_site
------
STY_YTRY_DT
STY_YTRY_HT
tr_city
------
Emsterdam
Try below
USE tempdb
--drop table travel,travel_2
create table travel (tr_id numeric, tr_site char(14), tr_city char(10))
insert into travel values (1,'STY_YTRY','Markham')
insert into travel values (2,'STY_YTRY_DT','Dehli')
insert into travel values (3,'STY_YTRY','NewYork')
insert into travel values (4,'STY_YTRY_HT','Emsterdam')
insert into travel values (5,'STY_YTRY','Toronto')
insert into travel values (6,'STY_YTRY','Markham')
create table travel_2 (tr_id numeric, tr_site char(10), tr_city char(8))
declare @Stablename varchar(400) ,@Dtablename varchar(400)
set @Stablename = 'travel'
set @Dtablename = 'travel_2'
declare @sql varchar(4000)=''
--set @sql =' Print ''Columns that has data greater that max_length are:'''+char(13)
select @sql =@sql + 'select distinct '+a.name+' from '+@Stablename+' where len('+a.name+') > '+convert(varchar,a.max_length)+char(13) from sys.columns a inner join sys.types b
on a.user_type_id = b.user_type_id
where object_id=object_id(@Dtablename) and b.name like '%char%'
print @sql
Exec (@sql)
No comments:
Post a Comment