Tuesday, October 7, 2008

Change Display Order After Deleting Record

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
--usp_Admin_DisplayOrder_DeleteUpdateDisplayOrder '56','','Tbl_Article','ArticleID'
--usp_Admin_DisplayOrder_DeleteUpdateDisplayOrder '','5,6','Tbl_Article','ArticleID'
--select * from tbl_Article
ALTER PROC [dbo].[usp_Admin_DisplayOrder_DeleteUpdateDisplayOrder]
@XmlStr VARCHAR(4000),@StrIDs varchar(4000),@Tablename varchar(100),@FieldName varchar(100)
as
Declare @XmlRecord INT
DECLARE @RetVal INT
SET @RetVal = -1

CREATE TABLE #Temp
(
RowID BIGINT IDENTITY(1,1),
ID BIGINT
)
CREATE TABLE #TempDisplayOrder (
DisplayOrder INT )

IF(@XmlStr <> '')
BEGIN
Exec sp_xml_preparedocument @XmlRecord OUTPUT, @XmlStr
Insert InTo #Temp(ID)
Select ID
From OpenXML (@XmlRecord, '/ROOT/DeleteLine', 2)
WITH (ID VARCHAR(10)) b
--SELECT * FROM #Temp
END
ELSE
BEGIN
Insert InTo #Temp(ID)
Select ID From SplitIDs(@StrIDs)
--SELECT * FROM #Temp
END


DECLARE @varMaxCount BIGINT

DECLARE @varCurrentCount BIGINT

DECLARE @varDisplayOrder INT
DECLARE @ID INT
DECLARE @strSql varchar(5000),@strSqlNew varchar(5000),@strSqlNew1 varchar(5000)

SET @varCurrentCount =1
SET @varDisplayOrder=0
SET @ID=0
SET @strSql=''
SET @strSqlNew=''
SET @strSqlNew1=''

SELECT @varMaxCount =max(RowID) FROM #Temp

WHILE (@varCurrentCount <=@varMaxCount)

BEGIN
SET @strSql=''
SET @strSqlNew=''
SET @strSqlNew1=''

SELECT @ID=ID FROM #Temp WHERE RowID=@varCurrentCount
SET @strSql = @strSql + ' SELECT DisplayOrder FROM '+@TableName+' WHERE '+@FieldName+'='+cast(@ID as varchar(100))

INSERT INTO #TempDisplayOrder(DisplayOrder)
EXEC(@strSql)
SELECT @varDisplayOrder=DisplayOrder FROM #TempDisplayOrder

SET @strSqlNew =@strSqlNew+' Update '+ @TableName +' Set DisplayOrder=DisplayOrder - 1 WHERE DisplayOrder > '+cast(@varDisplayOrder as Varchar(100))
SET @strSqlNew1 =@strSqlNew1+' DELETE FROM '+ @TableName +' WHERE '+@FieldName+'='+cast(@ID as varchar(100))
--print @strSqlNew
--print @strSqlNew1
EXEC(@strSqlNew)
EXEC(@strSqlNew1)
DELETE FROM #TempDisplayOrder
SET @varCurrentCount = @varCurrentCount + 1

END

No comments: