我有一张表格,格式如下: -
Column A Column B Column C
a b NULL
06/13/2012
08/11/2012
C D NULL
09/11/2011
E F NULL
06/13/2012
09/11/2012
需要输出的地方
Column A Column B Column C a b 06/13/2012 a b 08/11/2012 C D 09/11/2011 E F 06/13/2012 E F 09/11/2012
有没有办法可以循环更新A列和B列。即以不同的A列和B列的组合开始,并更新该列的剩余行,直到我们达到新的不同值。比较更新列A和列B与a和b,直到新值(C,D)
答案 0 :(得分:2)
INSERT INTO TableStack VALUES
( 'a', 'b',NULL)
,( '' ,'','06/13/2012')
,( '' ,'','08/11/2012')
,('C', 'D',NULL)
,( '' ,'','09/11/2011')
,('E', 'F',NULL)
,( '' ,'','06/13/2012')
,( '' ,'','09/11/2012')
--delete from TableStack
SELECT [Column A]
,[Column B]
,[Column C]
INTO #STACK
FROM TableStack
ALTER TABLE #STACK
ADD ModifiedA varchar(10),
ModifiedB varchar(10)
declare @t varchar(10)=''
update t
set ModifiedA=@t,
@t=@t+[column A]
from #STACK t
declare @t varchar(10)=''
update t
set ModifiedB=@t,
@t=@t+[column B]
from #STACK t
SELECT *,case when len(ModifiedA)=2 then right(ModifiedA,1)
when len(ModifiedA)=3 then right(ModifiedA,1) else ModifiedA end A,
case when len(ModifiedB)=2 then right(ModifiedB,1)
when len(ModifiedB)=3 then right(ModifiedB,1) else ModifiedB end B
INTO #StackNew
FROM #STACK
update s
set s.[column a]=s.A,
s.[Column B]=s.B
from #StackNew s
SELECT [column a],[Column B],[Column C] FROM #StackNew
WHERE [Column C] is not null
答案 1 :(得分:-1)
如果您的第一个表中有主键或任何唯一的行,那么您可以将其存储在临时表中并开始循环直到新值出现
您可以参考下面的查询来了解如何操作
Select ROW_NUMBER() OVER (ORDER BY ColumnC ) AS RowNumber,ColumnA, ColumnB, ColumnC --you are getting top table as asked in question
Into #Temp
From TableName
Declare @ColumnA VARCHAR(1)
Declare @ColumnB VARCHAR(1)
DECLARE @RowNumber INT
Declare @LastColumnA VARCHAR(1)
Declare @LastColumnA VARCHAR(1)
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 @RowNumber = RowNumber, @ColumnA = ColumnA, @ColumnB=ColumnB From #Temp ORDER BY ColumnC
IF ISNULL(@ColumnA,'') = ''
BEGIN
--update previous columns because its blank
UPDATE TableName SET ColumnA= @LastColumnA, ColumnB = @LastColumnB WHERE -- if primary key is there use it else use all where condition below
ColumnA = @ColumnA and ColumnB=@ColumnB and ColumnC=@ColumnC
END
ELSE
BEGIN
SET @LastColumnA = @ColumnA;
--Get New columns because its blank
END
--Do some processing here
Delete FROM #Temp Where RowNumber = @RowNumber
End
此查询未经过测试,您可以将其引用为逻辑