Skip to content

Instantly share code, notes, and snippets.

@jdaigle
Created March 30, 2015 13:39
Show Gist options
  • Save jdaigle/c4e2931e30b0e6c7a839 to your computer and use it in GitHub Desktop.
Save jdaigle/c4e2931e30b0e6c7a839 to your computer and use it in GitHub Desktop.
simple tsql counter table
-- CREATE TABLE [dbo].[Counter](
-- [id] [bigint] IDENTITY(1,1) NOT NULL,
-- [date] [date] NOT NULL,
-- [key] [varchar](100) NOT NULL,
-- [count] [int] NOT NULL,
-- CONSTRAINT [PK_Counter] PRIMARY KEY CLUSTERED ([id] ASC)
-- );
BEGIN TRAN
MERGE dbo.[Counter] as t
USING (SELECT 'mykey', '2015-03-30') AS s ([key], [date])
ON t.[key] = s.[key] AND t.[date] = s.[date]
WHEN MATCHED THEN
UPDATE SET t.[Count] = t.[Count] + 1 -- increment
WHEN NOT MATCHED THEN
INSERT ([key], [date], [Count])
VALUES ('mykey', '2015-03-30', 1);
COMMIT TRAN
SELECT * FROM dbo.[Counter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment