TSQL. Ottieni il totale bit a bit per molte colonne di fila
-
03-07-2019 - |
Domanda
Ho una tabella con 4 serie da 25 colonne in un concetto BIT. In realtà il campo è piccolo ma è 0 o 1 nei suoi dati.
Ecco il mio codice che è un tentativo di ottenere il totale per il primo gruppo di 25 cols.
Declare @rows int
, @ID uniqueidentifier
, @LocTotal bigint
select @rows = ( select count(*) from #t1 )
while @rows > 0
begin
print @rows
-- get that rowID
select @ID = (select top 1 recid from #t1)
select @LocTotal =
(select top 1
case when cbHPILoc1 = 1 then 1 else 0 end +
case when cbHPILoc2 = 1 then 2 else 0 end +
case when cbHPILoc3 = 1 then 4 else 0 end +
< snip >
case when cbHPILoc25 = 1 then 16777216 else 0 end
as Total
from dbo.MyTest_BitMap
where RecKey = @ID
)
print @ID
print @LocTotal
La mia uscita:
(5 row(s) affected)
5
67A16306-B27D-4882-88A2-1146CBAAA8D9
(1 row(s) affected)
4
F94929B9-3DA7-4AA3-96F6-728EF025B21C
Non riesco a ottenere il totale in @LocTotal
TIA
Soluzione
Penso che Tomalak ce l'abbia, motivo per cui l'ho modificato, ma se lo fai più o una volta, dal momento che tutto quel casino:
cbHPILoc1
+ cbHPILoc2 * 2
+ cbHPILoc3 * 4
+ ...
+ cbHPILoc25 * 16777216
è noioso e soggetto a errori, perché non farlo una volta come visione e testarlo accuratamente?
Quindi solo seleziona totale da viewname dove reckey =?
.
Altri suggerimenti
Perché è così complicato?
SELECT
RecKey,
cbHPILoc1
+ cbHPILoc2 * 2
+ cbHPILoc3 * 4
+ ...
+ cbHPILoc25 * 16777216
AS Total
FROM
dbo.MyTest_BitMap
WHERE
RecKey = @ID
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow