OK. I got a lot of help here earlier working with a SQL backend to a simple ... just not for me :( ... time clock solution for the small office I work in, so I'm back for more!
My table I'm currently working with consists of 6 columns:
I though I had figured out my IF NOT EXISTS INSERT ELSE UPDATE
statement from my last question, but now I'm trying to use it in a Stored Procedure, rather than a plain query window, with no success.
Basically a user clocking in is a no-brainer. However, if the user doesn't clock in, but they clock out for lunch, the statement needs to create the row instead of updating an existing row. Ok so here's my stored procedure:
ALTER PROCEDURE dbo.BreakOut
(
@userName varchar(50)
)
AS
IF EXISTS (SELECT * FROM Clock WHERE clockDate = GETDATE() AND userName = @userName)
BEGIN
UPDATE Clock SET breakOut = GETDATE()
WHERE clockDate = GETDATE() AND userName = @userName
END
ELSE
BEGIN
INSERT INTO Clock (clockDate, userName, breakOut)
VALUES (GETDATE(), @userName, GETDATE())
END
Here's my problem... If the user DID clock in for the day I get a primary key violation because the stored procedure is still trying to run the INSERT
part of the statement and never runs the UPDATE
line. I've tried it flipped with an IF NOT EXISTS
as well with the same result. What's the trick to get IF-ELSE to work in a stored procedure? Can this be done they way I'm thinking or do I have to study Merge
statement? My plan is to run the stored procedures from a simple Visual Basic program on each workstation. Maybe I'm getting in over my head :( To bad my boss is too cheap to just buy a time clock solution!
EDIT:
Thank you ALL for your help!! I'm falling in love with this site, questions get answers SO FAST!!! Here is my working stored procedure:
ALTER PROCEDURE dbo.BreakOut
(
@userName varchar(50)
)
AS
IF EXISTS (SELECT * FROM Clock WHERE DateDiff(dd, GetDate(),clockDate) = 0 AND userName = @userName)
BEGIN
UPDATE Clock SET breakOut = GETDATE()
WHERE DateDiff(dd, GetDate(),clockDate) = 0 AND userName = @userName
END
ELSE
BEGIN
INSERT INTO Clock (clockDate, userName, breakOut)
VALUES (GETDATE(), @userName, GETDATE())
END
Is this proper, or could it be improved more? Again Thank You ALL SO MUCH!!!
A single stored procedure can be used to select, add, update, and delete data from a database table.
No. Insert will only create a new row.
This is probably the problem right here: WHERE clockDate = GETDATE()
GetDate returns the current date AND the current time, which wouldn't match up with clockDate. You can compare the dates with DateDiff instead:
WHERE DateDiff(dd, GetDate(),clockDate) = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With