Domanda

Hi i have one table in sql server and i have added one bit for each week day. I have one property that's a date and i want to update all the table updating the bit depending of the dayofWeek of this date. I have read something about t-sql (datepart) but i dont know how can I do it, somebody can help me a little?

Here is a screenshot of my table

http://i.imgbox.com/adpsLL0D.jpg

For instance, in the firsts three records (2012-11-04, the last month, sunday) i want to update updating "prt_Dom" to 1.

Thanks.

È stato utile?

Soluzione 2

I'm not completely sure what you're trying to do, but perhaps something like this?

set language spanish
go

update dbo.MyTable
set
    prt_Lun = case when datename(dw, prt_fecha) = 'Lunes' then 0x1 else 0x0 end,
    prt_Mar = case when datename(dw, prt_fecha) = 'Martes' then 0x1 else 0x0 end,
    prt_Mie = case when datename(dw, prt_fecha) = 'Miércoles' then 0x1 else 0x0 end,
    prt_Jue = case when datename(dw, prt_fecha) = 'Jueves' then 0x1 else 0x0 end,
    prt_Vie = case when datename(dw, prt_fecha) = 'Viernes' then 0x1 else 0x0 end,
    prt_Sab = case when datename(dw, prt_fecha) = 'Sábado' then 0x1 else 0x0 end,
    prt_Dom = case when datename(dw, prt_fecha) = 'Domingo' then 0x1 else 0x0 end
where
    ...

If your logic is really this simple then you don't need the prt_% columns at all, because you can always derive the bit values from prt_fecha on demand. But I'm guessing that you're setting defaults here that you may override later, in which case the table would make sense.

And when working with dates be careful with culture-specific settings such as SET DATEFIRST and SET LANGUAGE.

Altri suggerimenti

SET DATEFIRST 1
UPDATE [tableName] SET [prt_Mar] = 1 WHERE DATEPART(dw, [prt_fecha]) = 2

For Wednesday, you would want

UPDATE [tableName] SET [column] = 1 WHERE DATEPART(dw, [prt_fecha]) = 3

SET DATEFIRST is relatively important as different cultures have different 'first day of the week' numbers. There are fully deterministic ways to extract a weekday if it's something you need to do regularly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top