Advertisement
Guest User

Untitled

a guest
Feb 26th, 2015
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.94 KB | None | 0 0
  1. DECLARE @object_id int;
  2. DECLARE @parent_object_id int;
  3. DECLARE @TSQL NVARCHAR(4000);
  4. DECLARE @COLUMN_NAME SYSNAME;
  5. DECLARE @is_descending_key bit;
  6. DECLARE @col1 BIT;
  7. DECLARE @action CHAR(6);
  8.  
  9. --SET @action = 'DROP';
  10. SET @action = 'CREATE';
  11.  
  12. DECLARE PKcursor CURSOR FOR
  13. select kc.object_id, kc.parent_object_id
  14. from sys.key_constraints kc
  15. inner join sys.objects o
  16. on kc.parent_object_id = o.object_id
  17. where kc.type = 'PK' and o.type = 'U'
  18. and o.name not in ('dtproperties','sysdiagrams') -- not true user tables
  19. order by QUOTENAME(OBJECT_SCHEMA_NAME(kc.parent_object_id))
  20. ,QUOTENAME(OBJECT_NAME(kc.parent_object_id));
  21.  
  22. OPEN PKcursor;
  23. FETCH NEXT FROM PKcursor INTO @object_id, @parent_object_id;
  24.  
  25. WHILE @@FETCH_STATUS = 0
  26. BEGIN
  27. IF @action = 'DROP'
  28. SET @TSQL = 'ALTER TABLE '
  29. + QUOTENAME(OBJECT_SCHEMA_NAME(@parent_object_id))
  30. + '.' + QUOTENAME(OBJECT_NAME(@parent_object_id))
  31. + ' DROP CONSTRAINT ' + QUOTENAME(OBJECT_NAME(@object_id))
  32. ELSE
  33. BEGIN
  34. SET @TSQL = 'ALTER TABLE '
  35. + QUOTENAME(OBJECT_SCHEMA_NAME(@parent_object_id))
  36. + '.' + QUOTENAME(OBJECT_NAME(@parent_object_id))
  37. + ' ADD CONSTRAINT ' + QUOTENAME(OBJECT_NAME(@object_id))
  38. + ' PRIMARY KEY'
  39. + CASE INDEXPROPERTY(@parent_object_id
  40. ,OBJECT_NAME(@object_id),'IsClustered')
  41. WHEN 1 THEN ' CLUSTERED'
  42. ELSE ' NONCLUSTERED'
  43. END
  44. + ' (';
  45.  
  46. DECLARE ColumnCursor CURSOR FOR
  47. select COL_NAME(@parent_object_id,ic.column_id), ic.is_descending_key
  48. from sys.indexes i
  49. inner join sys.index_columns ic
  50. on i.object_id = ic.object_id and i.index_id = ic.index_id
  51. where i.object_id = @parent_object_id
  52. and i.name = OBJECT_NAME(@object_id)
  53. order by ic.key_ordinal;
  54.  
  55. OPEN ColumnCursor;
  56.  
  57. SET @col1 = 1;
  58.  
  59. FETCH NEXT FROM ColumnCursor INTO @COLUMN_NAME, @is_descending_key;
  60. WHILE @@FETCH_STATUS = 0
  61. BEGIN
  62. IF (@col1 = 1)
  63. SET @col1 = 0
  64. ELSE
  65. SET @TSQL = @TSQL + ',';
  66.  
  67. SET @TSQL = @TSQL + QUOTENAME(@COLUMN_NAME)
  68. + ' '
  69. + CASE @is_descending_key
  70. WHEN 0 THEN 'ASC'
  71. ELSE 'DESC'
  72. END;
  73.  
  74. FETCH NEXT FROM ColumnCursor INTO @COLUMN_NAME, @is_descending_key;
  75. END;
  76.  
  77. CLOSE ColumnCursor;
  78. DEALLOCATE ColumnCursor;
  79.  
  80. SET @TSQL = @TSQL + ');';
  81.  
  82. END;
  83.  
  84. EXEC(@TSQL);
  85.  
  86. FETCH NEXT FROM PKcursor INTO @object_id, @parent_object_id;
  87. END;
  88.  
  89. CLOSE PKcursor;
  90. DEALLOCATE PKcursor;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement