显示标签为“selects”的博文。显示所有博文
显示标签为“selects”的博文。显示所有博文

2012年3月19日星期一

FK Constraint question

I have two tables
GroupUsers and Alias

GroupUsers
-GroupId
-AliasId
-UserId

Alias
-AliasId
-UserId

When a user joins a Group he selects a default Alias for his group, so I have put a foreign key constraint from the groupusers table to the alias table.

Now, if an alias is delete, is there any way through a foreign key constraint to set the value to null because all I've seen is Cascade and No Action

A better solution I'm looking for would be a way to run a script that would use the value in the UserId column from the GroupUsers table to select the top alias from the Alias table with a corresponding UserId (if exists) and set it to that. I'm unsure as to if this solution is even possible.
SQL Server doesn't support the SQL standard to set a FK to NULL, you would need to implement this, or your other solution, using a DELETE trigger on the Alias table.|||We support the SET DEFAULT and SET NULL options in SQL Server 2005. So for now, you will have to implement the logic using SPs or trigger code.

2012年2月24日星期五

First and Last day of week

Hi All
I have a report that brings back data based on the week a user selects.
The user will select a week number (e.g. week 1) then the report will automatically generate the first date (Monday) and last date of that week (Sunday), based on a whole week for the current year.
So, user selects week 3 for this year. The report generates the first date of the week: 16/01/2006 and last date of the week: 22/01/2006.

Note: I’m in the UK, so I am using the UK date format.

Try this:

Code/

Declare @.DOW As Char(10), @.weekdate Datetime, @.Monday DateTime, @.Sunday DateTime,

@.Working As Int, @.WeekNo Int

-- Find first day of year

Set @.WeekDate = (select DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

--Find a date in this week - any date

Set @.Working = @.WeekNo * 7

Select @.WeekDate = DateAdd(dd,@.Working,@.WeekDate)

Get day of week and subtract number of days to get the Monday

Set @.DOW = DateName(dw,@.Weekdate)

Set @.Monday = @.Weekdate

Set @.Monday = Case @.DOW

When 'Sunday' Then DateAdd(dd,-6,@.WeekDate)

When 'Saturday' Then DateAdd(dd,-5,@.WeekDate)

When 'Friday' Then DateAdd(dd,-4,@.WeekDate)

When 'Thursday' Then DateAdd(dd,-3,@.WeekDate)

When 'Wednesday' Then DateAdd(dd,-2,@.WeekDate)

When 'Tuesday' Then DateAdd(dd,-1,@.WeekDate)

Else @.Monday

End

Set @.Sunday = DateAdd(dd,6,@.Monday)

Select @.Monday, @.Sunday

/Code

You feed in @.WeekNo