SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Avatar_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
GO



CREATE procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
(
    @UserID  int,
    @Content image,
    @ContentType nvarchar(64),
    @ContentSize int,
    @Action  int,
    @SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
    -- Remove if already exists from tables: cs_Images, cs_UserAvatar
    DELETE cs_UserAvatar WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

    IF @Action = 0 OR @Action = 1 --If the action is 2 (delete) we can skip this part
    BEGIN

        -- Add new entry
        INSERT INTO cs_UserAvatar(UserID, SettingsID, Length, ContentType, [Content], DateLastUpdated) 
			SELECT @UserID, SettingsID, @ContentSize, @ContentType, @Content, GetDate() 
			FROM cs_UserProfile where UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
    END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Avatar_CreateUpdateDelete] to public 
go