J'ai une table comme celle-ci
ac asg asgc asgdt 1 abc abc 2012-06-01 00:00:00.000 1 NULL NULL 2012-06-02 00:00:00.000 1 xyz xyz 2012-07-01 00:00:00.000 1 NULL NULL 2012-07-02 00:00:00.000 2 NULL NULL 2012-07-03 00:00:00.000 2 lmn lmn 2012-08-01 00:00:00.000 2 NULL NULL 2012-08-02 00:00:00.000
Je dois enlever les nulls en répétant le text précédent, donc j'ai écrit
Declare @asgc nvarchar(10) UPDATE coalescetest SET @asgc = COALESCE(asgc, @asgc), asgc = COALESCE(asgc, @asgc)
Ce code m'a donné la sortie ci-dessous
ac asg asgc 1 abc abc 1 NULL abc 1 xyz xyz 1 NULL xyz 2 NULL xyz 2 lmn lmn 2 NULL lmn
Le problème ici est, il devrait répéter le text précédent au niveau du count. Comme on le voit, 'xyx'
valeur 'xyx'
pour ac
1 est répétée en ac
2. Cela ne devrait pas arriver. La sortie idéale devrait être comme ça
ac asg asgc 1 abc abc 1 NULL abc 1 xyz xyz 1 NULL xyz 2 NULL NULL 2 lmn lmn 2 NULL lmn
Donc, j'ai écrit une boucle au niveau ac
. Mais c'est tuer la performance. Quelqu'un peut-il s'il vous plaît suggenst un moyen de sortir. Merci à l'avance.
Cela marche:
declare @tab table (ac int not null, asg char(3) null, asgc char(3) null, asgdt datetime not null) insert into @tab(ac,asg,asgc,asgdt) values (1,'abc','abc','2012-06-01 00:00:00.000'), (1,NULL,NULL,'2012-06-02 00:00:00.000'), (1,'xyz','xyz','2012-07-01 00:00:00.000'), (1,NULL,NULL,'2012-07-02 00:00:00.000'), (2,NULL,NULL,'2012-07-03 00:00:00.000'), (2,'lmn','lmn','2012-08-01 00:00:00.000'), (2,NULL,NULL,'2012-08-02 00:00:00.000') update t1 set asgc = t2.asgc from @tab t1 inner join @tab t2 on t1.ac = t2.ac and --Belong to same account t2.asgc is not null and --Has a useful value t2.asgdt < t1.asgdt --Is an earlier row left join @tab t3 on t1.ac = t3.ac and --Belong to same account t3.asgc is not null and --Has a useful value t3.asgdt < t1.asgdt and --Is an earlier row t3.asgdt > t2.asgdt --But occurs later than t2 where t1.asgc is null and --Needs a fill-in value t3.ac is null --And no better matching row was found for the replacement select * from @tab
Résultat:
ac asg asgc MysteriousUnamedColumn ----------- ---- ---- ----------------------- 1 abc abc 2012-06-01 00:00:00.000 1 NULL abc 2012-06-02 00:00:00.000 1 xyz xyz 2012-07-01 00:00:00.000 1 NULL xyz 2012-07-02 00:00:00.000 2 NULL NULL 2012-07-03 00:00:00.000 2 lmn lmn 2012-08-01 00:00:00.000 2 NULL lmn 2012-08-02 00:00:00.000
Notez que, à aucun moment, je ne me fie à l'ordre dans lequel la mise à jour est réellement appliquée à la table.
Je viens de réaliser que ma réponse, bien sûr, n'utilise pas réellement COALESCE
, comme le titre de la question. Mais, TBH, c'était le mauvais outil pour le travail en cours de toute façon. Vous pouvez réécrire la requête ci-dessus pour utiliser un COALESCE
, et le mettre à jour toutes les lignes plutôt que seulement celles avec des valeurs NULL
, mais je ne peux pas penser à une raison saine de le faire.