开发者

How to get a week number from a date in SQL Server 2005

for every row in TableA i have a date and a week number field. The date field is already populated and i was hoping there would be a way to automatically fill the Week number field aswell instead of having to do it manually.

an example of the date is as follows: 20111007

hope you c开发者_运维技巧an help, cheers :)


With this syntax you can retrieve the week for a date.

SELECT datepart(week, '20111007'), datepart(iso_week, '20111007')

iso_week only works from sqlserver 2008 though.

You really should consider making the week field into a computed column. It will make your life so much easier (I would use this solution).

This would be your syntax:

alter table <yourtable> add week1 as datepart(week, <yourdatecolumn>)

Should you for some reason be prevented from making database changes, you could use this:

UPDATE <table>
SET <weekcolumn> = datepart(week, <yourdate>)
WHERE week is null and <yourdate> is not null

Problem is that if the date change, the week will still remain the same and the week will not be available until this script is used unless the week is updated with a trigger.

You could also create a view to show all columns and add the week as a computed field, this would also be a valid solution. Although it is good practice to list the columns instead of using wildchar(*), I used it because i don't know your columns.

CREATE VIEW v_yourview as
SELECT *, datepart(week, <yourdate>) week1 FROM <table>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜