CREATE PROCEDURE [dbo].[spSaveSetting]
	@parent_id int = 0,
	@id int = 0 OUTPUT,
	@name varchar(50) = '',
	@value xml = '',
	@enabled bit = 1
AS
BEGIN
	SET @name = ltrim(rtrim(@name))
	IF NOT EXISTS ( SELECT 1 FROM tblSettings WHERE id = @parent_id )
		RAISERROR('Node {%d} does not exist', 16, 1, @parent_id)
	ELSE IF @id <> 0 AND NOT EXISTS ( SELECT 1 FROM tblSettings WHERE id = @id )
		RAISERROR('Node with [id] of {%d} does not exist', 16, 1, @id)
	ELSE IF @name = ''
		RAISERROR('@name cannot be empty', 16, 1)
	--ELSE IF @id <> 0 AND @parent_id = @id
	--	RAISERROR('Multiple root nodes are not currently supported', 16, 1)
	--ELSE IF EXISTS (
	--	SELECT 1 FROM tblSettings
	--	WHERE
	--		parent_id = @parent_id AND
	--		name = @name AND
	--		id <> @id
	--	)
	--	RAISERROR('A node with the same parent and name already exists', 16, 1)
	--TODO: Prevent circular hierarchies
	ELSE BEGIN
		IF @id = 0 BEGIN
			INSERT tblSettings
			(
				parent_id,
				name,
				value,
				enabled
			)
			VALUES
			(
				@parent_id,
				@name,
				@value,
				@enabled
			)
			SELECT @id = scope_identity()
		END ELSE BEGIN
			UPDATE tblSettings
			SET
				parent_id = @parent_id,
				name = @name,
				value = @value,
				enabled = @enabled
			WHERE id = @id
		END
	END
END