Friday 4 December 2009

Dynamic query to get all columns value from a table except the primary key column

-------------------------------------------------------------------------------

declare @qry nVarchar(4000)

@tblName Varchar(100)

@i int

@cnt int

declare @colNames nvarchar(4000)

set @colNames = ''set @qry = 'select name from syscolumns where id = (select id from sysobjects where name ='+ @tblName

create table #tmp(ID int identity(1,1), ColName Varchar(60))

insert into #tmp(ColName)

exec (@qry)

select @cnt = count(id) from #tmp

while (@i <= @cnt)

begin

select ColName from #tmp where id = @i

set @colNames = @colNames + (select ColName from #tmp where id = @i)

set @colNames = @colNames + ','

set @i = @i + 1

end

set @colNames = substring(@colNames, 1, len(@colNames)-1)

set @qry = ''set @qry = 'select ' + @colNames+' from ' + @tblName

exec (@qry)

No comments:

Post a Comment