Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Find a record
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Title:
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01287531
Message ID:
01287572
Views:
11
>I used ideas from both Borislav's and Naomi's post.
>This is the code that I think will work for me. I will have to test it better to be sure.
>
>@fk and @clock are passed into the SP, and are int and datetime respectively.
>
>
>SELECT	@Count = COUNT(*),
>	@MinTime = MIN([Clock]),
>	@MaxTime = Max([Clock])
>FROM	[MyTable]
>WHERE	[Fk] = @fk AND
>	YEAR([Clock]) = YEAR(@clock) AND
>	MONTH([Clock]) = MONTH(@clock) AND
>	DAY([Clock]) = DAY(@clock)
>
>IF @Count < 2 BEGIN
>	PRINT 'INSERT'
>END ELSE BEGIN
>	DECLARE @PkToUpdate AS uniqueidentifier
>
>	IF (@clock BETWEEN @MinTime AND @MaxTime) BEGIN
>		PRINT 'DO NOT DO ANYTHING BECAUSE IT IS BETWEEN'
>	END ELSE IF (@clock < @MinTime) BEGIN
>		PRINT 'UPDATE row where Clock is @MinTime'
>		SET @PkToUpdate = (	SELECT	TOP(1) [PK] FROM [MyTable]
>						WHERE	[FK] = @fk AND
>							YEAR([Clock]) = YEAR(@clock) AND
>							MONTH([Clock]) = MONTH(@clock) AND
>							DAY([Clock]) = DAY(@clock)
>						ORDER BY [Clock] ASC)
>	END ELSE BEGIN
>		PRINT 'UPDATE row where Clock is @MaxTime'
>		SET @PkToUpdate = (	SELECT	TOP(1) [PK] FROM [MyTable]
>						WHERE	[FK] = @fk AND
>							YEAR([Clock]) = YEAR(@clock) AND
>							MONTH([Clock]) = MONTH(@clock) AND
>							DAY([Clock]) = DAY(@clock)
>						ORDER BY [Clock] DESC)
>	END
>
>	IF (@PkToUpdate IS NOT NULL) BEGIN
>		PRINT 'Update!!!!!'
>		PRINT @PkToUpdate
>	END
>END
>
>
>Is there a way to make this faster, better or prettier?

Do you want to only update one record even if you have multiple records with the same MinTime or MaxTime? Or this scenario is impossible?

Instead of Select top 1 you may use select .. where clock = @MinTime, I think.

BTW, if you don't need to return PK to Update, then Borislav's idea would work as is.
If it's not broken, fix it until it is.


My Blog
Previous
Reply
Map
View

Click here to load this message in the networking platform