Friday, January 16, 2015

more on upsert (maybe insert or maybe update) logic in T-SQL

Let me start by saying that I'm just learning that T-SQL is the SSMS Microsoft SQL. I've just been calling it MSSQL but I guess that's wrong. I guess T-SQL is "Transact-SQL" and thus it has the T. While I'm also babbling let me say that GETDATE() is the DateTime.Now of T-SQL. Alright, now that I have those things out of my need to document, I'd like to mention that I tried to write a merge yesterday as suggested here and it ended up looking like this:

DECLARE @upsert TABLE
(
   FriendlyName nvarchar(50),
   Markup nvarchar(max),
   ImmediateMomentInTime datetime
)
INSERT INTO @upsert(FriendlyName, Markup, ImmediateMomentInTime) VALUES ('Log4NetConfig',
'<log4net><appender name=\"RollingFileAppender\" type=\"log4net.Appender.RollingFileAppender\"><file...'
, GETDATE())
MERGE INTO Properties USING @upsert ON Property_Name = FriendlyName
WHEN MATCHED THEN
UPDATE SET Property_Value = Markup, Mod_Date = ImmediateMomentInTime
WHEN NOT MATCHED THEN
INSERT (Property_Name, Property_Value, Mod_Date) VALUES (FriendlyName, Markup, ImmediateMomentInTime);

 
 

When I tried to actually run the SQL I got this error:

Incorrect syntax near 'MERGE'. You may need to set the compatibility level of the current database to a higher value to enable this feature. See help for the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.

 
 

When I asked my boss if it was alright to open up permissions he pointed out to me that there was already a stored procedure that more or less did what I was attempting. It didn't use merge as it turned out. Instead it either ran an update or an insert based upon if/else logic defined like this:

IF EXISTS (SELECT 1 FROM dbo.Properties WHERE Property_Name = 'Log4NetConfig')

No comments:

Post a Comment