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:
01287543
Views:
12
This message has been marked as a message which has helped to the initial question of the thread.
>Consider this table:
>pk uniqueidentifier
>fk bigint
>clock datetime
>
>I need an SP that can do the following:
>If there are zero records for that day, insert a record.
>If there is one record for that day, insert a record.
>If there are two or more records for that day:
> - do nothing if the time falls between the min and max time for that day
> - update the min time record if the passed clock is less than the min time for that day
> - update the max time record if the passed clock is greater than the max time for that day
>
>This is what I've got. but I am not sure how to find the correct record (if needed) to update
>
>SELECT @count = count(*) FROM mytable
>WHERE fk=@fk AND
>YEAR(clock) = YEAR(@clock) AND
>MONTH(clock) = MONTH(@clock) AND
>DAY(clock) = DAY(@clock)
>
>IF @count<2 BEGIN
>	// insert this is easy
>END ELSE BEGIN
>	// find the correct @pk to update
>END
>
>
>Any help appreciated.



Not sure what you want:
SELECT @count   = count(*),
       @MinTime = MIN(DateTimeField),
       @MaxTime = Max(DateTimeField),
       FROM mytable 
WHERE fk=@fk AND
YEAR(clock) = YEAR(@clock) AND
MONTH(clock) = MONTH(@clock) AND
DAY(clock) = DAY(@clock)

IF @count<2 BEGIN
	// insert this is easy
END ELSE BEGIN
    IF @MinTime -- Here I am not sure what you mean with "if the passed clock is less than the min time for that day"
       BEGIN
           UPDATE .....
                  WHERE fk=@fk AND
                  YEAR(clock) = YEAR(@clock)   AND
                  MONTH(clock) = MONTH(@clock) AND
                  DAY(clock) = DAY(@clock)     AND
                  DateTimeField = @MinTime
       END
     
    IF @MaxTime -- Here I am not sure what you mean with "if the passed clock is greater than the min time for that day"
       BEGIN
           UPDATE .....
                  WHERE fk=@fk AND
                  YEAR(clock) = YEAR(@clock)   AND
                  MONTH(clock) = MONTH(@clock) AND
                  DAY(clock) = DAY(@clock)     AND
                  DateTimeField = @MaxTime
       END

END
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform