sql server - Query regarding T-SQL programming -


recently in interview came across question. here posting same, please me query. have table 1 column. in column values following. have is, replace nulls below value a, replace null below value b b replace nulls below value c c. not know approach solve problem. tried using sub-queries , string functions nothing worked out. in advance.

a null null b null null c null null 

ok lets assume table name test , lets assume records returned in order above (which in practice not mentioned many comments) lets assume column name a

so create table following query

create table test(a char(1)) go 

then insert records described above this

insert test(a) values  ('a') ,(null) ,(null) ,('b') ,(null) ,(null) ,('c') ,(null) ,(null) go 

now since said t-sql question can use query solve problem below

declare @val char(1), @last_val char(1);  declare cur cursor   select test; open cur  fetch next cur @val  while @@fetch_status=0 begin   if @val null begin     update test set = @last_val     current of cur;    end else begin     set @last_val = @val   end    fetch next cur @val end  close cur deallocate cur 

so when run

select test 

your result this

a a b b b c c c 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -