Created
March 30, 2015 13:39
-
-
Save jdaigle/c4e2931e30b0e6c7a839 to your computer and use it in GitHub Desktop.
simple tsql counter table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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