如何从 SQL Server 2005 中的日期获取周数

发布于 2024-12-02 15:33:32 字数 154 浏览 0 评论 0原文

对于表 A 中的每一行,我都有一个日期和一个周数字段。日期字段已经填充,我希望有一种方法可以自动填充周数字段,而不必手动填充。

日期示例如下: 20111007

希望你能帮忙,干杯:)

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 can help, cheers :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

時窥 2024-12-09 15:33:32

使用此语法,您可以检索日期的周数。

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

iso_week 仅适用于 sqlserver 2008。

您确实应该考虑将周字段放入计算列中。它将使您的生活变得更加轻松(我会使用这个解决方案)。

这将是您的语法:

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

如果您由于某种原因被阻止进行数据库更改,您可以使用以下内容:

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

问题是,如果日期更改,星期仍将保持不变,并且在使用此脚本之前星期将不可用除非本周通过触发器更新。

您还可以创建一个视图来显示所有列并将周添加为计算字段,这也是一个有效的解决方案。尽管列出列而不是使用 wildchar(*) 是一种很好的做法,但我使用它是因为我不知道您的列。

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文