CREATE PROCEDURE [dbo].[USP_ChartsTemplate_AddOrUpdate]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@chartName VARCHAR(300), 
	@symbol VARCHAR(50),
	@resolution VARCHAR(10),
	@lastModified DATETIME,
	@content TEXT, 
	@chartId BIGINT = NULL
AS
	MERGE [ChartsTemplate] as ct
	USING (VALUES(@chartId, @client,@user, @chartName,@symbol,@resolution,@lastModified,@content)) as s ([ChartId], [Client], [User], [ChartName], [Symbol], [Resolution], [LastModified], [Content])
	ON ct.[Id] = s.[ChartId] AND ct.[User] = s.[User] AND ct.[Client]=s.[Client] 
	WHEN MATCHED
		THEN UPDATE 
			SET [ChartName] = s.[ChartName],
				[Symbol] = s.[Symbol],
				[Resolution] = s.[Resolution],
				[LastModified] = s.[LastModified], --NEED REVIEW: possiblyu better fill from db like GETUTCDATE()
				[Content] = s.[Content]
				
	WHEN NOT MATCHED THEN 
		INSERT ([Client], [User], [ChartName], [Symbol], [Resolution], [LastModified], [Content])
		VALUES (@client,  @user,  @chartName,  @symbol,  @resolution,  @lastModified,  @content)
	;

	SELECT SCOPE_IDENTITY()
RETURN 0