Friday, October 8, 2010

Drop Constraint pada SQL Server

Nah kawan - kawan smua, klo sblum nya gw pernah nge post soal Drop primary key sekarang gw mau nge post drop saudara nya primary key yaitu Constraint

bagi yang blum denger Constraint, ya brarti loe perlu lebih dalem lagi belajar database nya, klo soal penjelasan nya pasti loe smua bisa mudah deh dapetin nya apalagi ada mbah google.. klo gw sih mau kasih yg kira-kira sulit di cari orang tp smua butuh.. hehe...

langsung aje kali yaa.. sperti biasa loe copy paste aja dah.. nih :

CREATE PROCEDURE [dbo].[DropUniqueConstraint]
@tableName NVarchar(255),
@columnName NVarchar(255)
AS
DECLARE @IdxNames CURSOR

SET @IdxNames = CURSOR FOR
select sysindexes.name from sysindexkeys,syscolumns,sysindexes
WHERE
syscolumns.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
AND sysindexkeys.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
AND sysindexes.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
AND syscolumns.name=@columnName
AND sysindexkeys.colid=syscolumns.colid
AND sysindexes.[indid]=sysindexkeys.[indid]
AND (
SELECT COUNT(*) FROM sysindexkeys AS si2
WHERE si2.id=sysindexes.id
AND si2.indid=sysindexes.indid
)=1

OPEN @IdxNames
DECLARE @IdxName Nvarchar(255)
FETCH NEXT FROM @IdxNames INTO @IdxName

WHILE @@FETCH_STATUS = 0 BEGIN
DECLARE @dropSql Nvarchar(4000)

SET @dropSql=
N'ALTER TABLE ['+@tableName+ N']
DROP CONSTRAINT ['+@IdxName+ N']'
EXEC(@dropSql)

FETCH NEXT FROM @IdxNames
INTO @IdxName
END
CLOSE @IdxNames
DEALLOCATE @IdxNames


nah.. loe jalanin dah tuh..
abis itu klo mau eksekusi nya loe tinggal ketik :

EXEC [dbo].[DropUniqueConstraint]
@tableName='TargetTable',
@columnName='TargetColumn'

selesai deh..

jangan lupa kasih koment yaa...
dah mampir masa comment aja pelit sih :)
gak perlu panjang2, biar gw lebih semangat tuk ngepost yg lebih bermanfaat lagi..

No comments:

Post a Comment