Advertisement
thepirat000

ALL SQL MASTERS 09/09/2015

Aug 29th, 2013
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 84.50 KB | None | 0 0
  1. USE master
  2. GO
  3.  
  4. /*
  5. Drop Procedure SP_SELECT_ALL
  6. Drop Procedure sp_ppinScriptLlavesForaneas
  7. Drop Procedure sp_ppinScriptTabla
  8. Drop Procedure SP_ppinAddDrop_ForeignKeys
  9. Drop Procedure SP_ppinGenera_Insert
  10. Drop Procedure sp_longitud
  11. Drop Procedure sp_doc_comment
  12. Drop Procedure sp_drop
  13. Drop Procedure sp_ppinNombreTablaTemp
  14. Drop Procedure sp_ppinSelectFromWhereForaneo
  15. Drop Procedure sp_ppinInsertaObjetoError
  16. Drop Procedure sp_ppinDependenciaSP
  17. Drop Procedure sp_ppinGeneraScriptObjeto
  18. Drop Procedure sp_GenerateConstantScript
  19. */
  20.  
  21. If exists ( Select * From sysobjects where name = 'SP_SELECT_ALL' )
  22.     Drop Procedure SP_SELECT_ALL
  23. GO
  24.  
  25. Create procedure SP_SELECT_ALL
  26. (
  27. @objname varchar(500),
  28. @filtro varchar(50) = '',
  29. @campo varchar(50) = ''
  30. )
  31. as
  32. /* Federico Colombo */
  33. Declare @sysobj_type char(2), @columna varchar(100)
  34. Declare @vchCommand varchar(700)
  35. Declare @vchNombreObjname varchar(256)
  36. Declare @vchNombreBaseDatos varchar(256)
  37. Declare @vchQuery varchar(512)
  38. Declare @groupid int
  39.  
  40. Set @vchNombreBaseDatos = ''
  41.  
  42. Create table #tmpColumna
  43. (
  44.     vchColumna varchar(256) null
  45. )
  46.  
  47. create table #helpIndex
  48. (
  49.     index_name          sysname collate database_default NOT NULL,
  50.     index_description       varchar(210),
  51.     index_keys          nvarchar(2126) collate database_default NOT NULL
  52. )
  53.  
  54. If isnumeric(@objname) = 0 --No es un numero
  55. Begin
  56.     If @objname like '%..%'
  57.     Begin      
  58.         Select @vchNombreBaseDatos = substring(@objname, 1, CHARINDEX('.',@objname) - 1)
  59.         Select @vchNombreObjname = substring(@objname, CHARINDEX('.',@objname) + 2, len(@objname))
  60.     End
  61.     Else
  62.     Begin
  63.         Set @vchNombreObjname = @objname
  64.     End
  65. End
  66. Else
  67. Begin
  68.     Set @vchNombreObjname = @objname
  69. End
  70.  
  71. Select @sysobj_type = xtype from sysobjects where id = object_id(@vchNombreObjname)
  72. If @vchNombreBaseDatos is null or @vchNombreBaseDatos = ''
  73. Begin
  74.     Set @vchCommand = 'Select'
  75.     Set @vchCommand = @vchCommand + ' * From ' + @vchNombreObjname + ' '
  76. End
  77. Else
  78. Begin
  79.     Set @vchCommand = 'Select'
  80.     Set @vchCommand = @vchCommand + ' * From ' + @vchNombreBaseDatos + '..' + @vchNombreObjname + ' '
  81. End
  82. SET NOCOUNT ON
  83.  
  84. -- Si sólo pasan un número
  85. If (@filtro = '' And @campo = '' And IsNumeric(@vchNombreObjname) = 1)
  86. Begin
  87.     Set @vchCommand = 'Select * From Constant Where Id = ' + @objname + char(13) + char(10) + char(13) + char(10)
  88.     Create Table #group ( groupid int )
  89.     Insert into #group
  90.     Exec ('Select Top 1 ConstantGroupId From ConstantGroupConstant Where ConstantId = ' + @objname)
  91.     Select Top 1 @groupid = groupid from #group
  92.     Set @vchCommand = @vchCommand + 'Select c.* From ConstantGroupConstant cgc, Constant c where cgc.ConstantId = c.Id And cgc.ConstantGroupId = ' + Cast(@groupid as nvarchar)
  93. End
  94.  
  95. --Revisar si el nombre correspone a una base de datos
  96. If exists ( Select * From master..sysdatabases Where name = @vchNombreObjname )
  97. Begin
  98.     Set @vchCommand = 'Use ' + @vchNombreObjname
  99. End
  100.  
  101. If @filtro <> ''        --Se proporcionó un filtro
  102. Begin
  103.     if @campo = ''  --pero No se indicó número ni nombre de campo
  104.     Begin
  105.         --Adquiero el primer nombre de campo con llave primaria (Si y sólo si Si es tabla):
  106.         If @sysobj_type in ('S ','U ')      -- Tabla
  107.         Begin
  108.             --Tomo el primer campo de la llave principal           
  109.             If @vchNombreBaseDatos is null or @vchNombreBaseDatos = ''
  110.             Begin
  111.                 Insert into #helpIndex
  112.                 Exec ('sp_helpindex ''' + @vchNombreObjname + '''')
  113.             End
  114.             Else
  115.             Begin
  116.                 Insert into #helpIndex
  117.                 Exec ('sp_helpindex ''' + @vchNombreBaseDatos + '..' + @vchNombreObjname + '''')
  118.             End
  119.             -- Adquiero el primer campo de la llave primaria (si existe)
  120.             Select @columna = Case CharIndex(',', index_keys) When 0 Then index_keys Else Left(index_keys, CharIndex(',', index_keys) - 1) End
  121.             From #helpIndex
  122.             Where index_name like 'PK_%'
  123.  
  124.             If @columna IS NULL -- Si no existe, tomo el primer campo de la tabla
  125.             Begin
  126.                 If @vchNombreBaseDatos is null or @vchNombreBaseDatos = ''
  127.                 Begin
  128.                     -- Tomo el nombre del campo número 1 de la tabla @objname
  129.                     Select @columna = c.name
  130.                     From SysObjects o, SysColumns c
  131.                     Where o.id = object_id(@objname)
  132.                     And o.id = c.id
  133.                     And c.colid = 1
  134.                 End
  135.                 Else--Si se esta enviando la base de datos
  136.                 Begin
  137.                     Set @vchQuery = 'Select c.name ' + char(13)
  138.                     Set @vchQuery = @vchQuery + 'From ' + @vchNombreBaseDatos + '..' + 'SysObjects o, ' + @vchNombreBaseDatos + '..' + 'SysColumns c ' + char(13)
  139.                     Set @vchQuery = @vchQuery + 'Where o.id = object_id(' + char(39) + @vchNombreBaseDatos + '..' + @vchNombreObjname + char(39) + ') ' + char(13)
  140.                     Set @vchQuery = @vchQuery + 'And o.id = c.id ' + char(13)
  141.                     Set @vchQuery = @vchQuery + 'And c.colid = 1 ' + char(13)
  142.                    
  143.                     Insert into #tmpColumna ( vchColumna )
  144.                     exec ( @vchQuery )
  145.                     If exists ( Select * From #tmpColumna )
  146.                     Begin
  147.                         Select @columna = vchColumna From #tmpColumna
  148.                     End
  149.                 End
  150.             End
  151.         End
  152.         Else If @sysobj_type in ('V ')      -- Vista (no hay llave primaria)
  153.         Begin
  154.             If @vchNombreBaseDatos is null or @vchNombreBaseDatos = ''
  155.             Begin
  156.                 -- Tomo el nombre del campo número 1 de la tabla @objname
  157.                 Select @columna = c.name
  158.                 From SysObjects o, SysColumns c
  159.                 Where o.id = object_id(@objname)
  160.                 And o.id = c.id
  161.                 And c.colid = 1
  162.             End
  163.             Else
  164.             Begin
  165.                 Set @vchQuery = 'Select c.name ' + char(13)
  166.                 Set @vchQuery = @vchQuery + 'From ' + @vchNombreBaseDatos + '..' + 'SysObjects o, ' + @vchNombreBaseDatos + '..' + 'SysColumns c ' + char(13)
  167.                 Set @vchQuery = @vchQuery + 'Where o.id = object_id(' + char(39) + @vchNombreBaseDatos + '..' + @vchNombreObjname + char(39) + ') ' + char(13)
  168.                 Set @vchQuery = @vchQuery + 'And o.id = c.id ' + char(13)
  169.                 Set @vchQuery = @vchQuery + 'And c.colid = 1 ' + char(13)
  170.                
  171.                 Insert into #tmpColumna ( vchColumna )
  172.                 exec ( @vchQuery )
  173.                 If exists ( Select * From #tmpColumna )
  174.                 Begin
  175.                     Select @columna = vchColumna From #tmpColumna
  176.                 End
  177.             End
  178.         End
  179.     End
  180.     Else    -- Se indicó un campo para filtrar
  181.     Begin
  182.         -- FEDE: Comprobar si existe columna
  183.         If IsNumeric(@campo) = 1            -- Se indicó NUMERO de campo
  184.             -- Necesito el nombre del campo número @campo
  185.             Select @columna = c.name
  186.             From SysObjects o, SysColumns c
  187.             Where o.id = object_id(@objname)
  188.             And o.id = c.id
  189.             And c.colid = Convert(SmallInt, @campo)
  190.         Else                            -- Se indicó Nombre de campo
  191.             Set @columna = @campo
  192.     End
  193.     Set @vchCommand = @vchCommand + 'Where ' + @columna + ' '
  194.     If IsNumeric(@filtro) = 0               -- No es un número, poner LIKE comillas
  195.         Set @vchCommand = @vchCommand + 'LIKE ''%' + @filtro + '%'' '
  196.     Else
  197.         Set @vchCommand = @vchCommand + '= ''' + @filtro + ''' '
  198. End
  199. Print @vchCommand + char(13) + char(10) + char(13) + char(10)
  200. SET NOCOUNT OFF
  201. EXECUTE (@vchCommand)
  202. GO
  203.  
  204. -- Función que partir de una tabla y un ID de indice de la misma
  205. -- devuelve todos los campos involucrados en el índice entre paréntesis y separados por coma
  206. If exists ( select * from sysobjects where name = 'sp_ppinCamposIndice' )
  207.     Drop Function sp_ppinCamposIndice
  208. GO
  209. Create Function sp_ppinCamposIndice
  210. (
  211.     @vchDbName varchar(128),
  212.     @vchTabla sysname,
  213.     @indid int
  214. )
  215. Returns Varchar(512)
  216. As
  217. /* Federico Colombo */
  218. Begin
  219.     -- Función que partir de una tabla y un ID de indice de la misma
  220.     -- devuelve todos los campos involucrados entre paréntesis y separados por coma
  221.     Declare @ret varchar(512), @nv nvarchar(128), @i int
  222.     Select @ret = '(', @i = 1
  223.    
  224.     Set @nv = index_col(@vchDbName + '..' + @vchTabla, @indid, @i) 
  225.     While not @nv is null
  226.     Begin
  227.         Set @ret = @ret + @nv + ', '
  228.  
  229.         Set @i = @i + 1
  230.         Set @nv = index_col(@vchDbName + '..' + @vchTabla, @indid, @i) 
  231.     End
  232.  
  233.     Set @ret = Left(@ret, len(@ret) - 1) + ')'
  234.     return @ret
  235. End
  236. GO
  237.  
  238.  
  239. -- Función que dado un tipo (de datos) y su longitud devuelve el texto que lo describe
  240. If exists ( select * from sysobjects where name = 'sp_ppinTipoLongitud' )
  241.     Drop Function sp_ppinTipoLongitud
  242. GO
  243. create Function sp_ppinTipoLongitud
  244. (
  245.     @xtype int,
  246.     @length int,
  247.     @isnullable int
  248. )
  249. Returns Varchar(512)
  250. As
  251.  
  252. /* Federico Colombo */
  253. Begin
  254.     -- Función que a partir de un tipo de datos y una logitud, devuelve el texto del tipo.
  255.     -- Por ejemplo: para xtype=varchar y length=10 devolverá "varchar(10)"
  256.     Declare @ret varchar(512)
  257.     Set @ret = ''
  258.  
  259.     Select @ret = Type_Name(@xtype) +
  260.     Case When Type_Name(@xtype) in ('varchar', 'char') Then
  261.             Case When @length = -1 then '(max)' else '(' + Convert(varchar, @length) + ')' end
  262.          When Type_Name(@xtype) in ('nvarchar', 'nchar') Then
  263.             Case When @length = -1 then '(max)' else '(' + Convert(varchar, @length/2) + ')' end
  264.          Else '' End + ' ' +
  265.     Case @isnullable When 1 Then 'NULL' Else 'NOT NULL' End
  266.    
  267.     Return @ret
  268. End
  269.  
  270. GO
  271.  
  272. -- Devuelve las llaves foráneas de una tabla especificada
  273. If exists ( select * from sysobjects where name = 'sp_ppinScriptLlavesForaneas' )
  274.     Drop Procedure sp_ppinScriptLlavesForaneas
  275. GO
  276. Create Procedure sp_ppinScriptLlavesForaneas
  277. (
  278.     @vchTabla sysname,
  279.     @vchResultado varchar(8000) output
  280. )
  281. AS
  282. /* Federico Colombo */
  283. Begin
  284.  
  285.     DECLARE @tmpFK table(
  286.         TablaF sysname,
  287.         TablaR sysname,
  288.         ColF sysname,
  289.         ColR sysname,
  290.         FKName sysname)
  291.  
  292.     -- obtengo las llaves foraneas en @vchForeign
  293.     Declare @vchForeign varchar(8000), @FKName sysname, @vchColumnasF varchar(4000), @vchColumnasR varchar(4000), @ColF sysname, @ColR sysname
  294.     Declare @vchTemp varchar(1000), @TablaR sysname
  295.  
  296.     Insert into @tmpFK
  297.     Select TablaF.name AS TablaF, TablaR.name AS TablaR, ColF.name AS ColF, ColR.name AS ColR, ofk.name AS FKName
  298.     From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR,
  299.     syscolumns ColF, syscolumns ColR
  300.     Where TablaF.name = @vchTabla
  301.     And ofk.id = fk.constid
  302.     And TablaF.id = fk.fkeyid
  303.     And TablaR.id = fk.rkeyid
  304.     And ColF.id = TablaF.id And ColF.colid = fk.fkey
  305.     And ColR.id = TablaR.id And ColR.colid = fk.rkey
  306.     order by FKName
  307.  
  308.     Set @vchForeign = ''
  309.     While Exists ( Select * From @tmpFK )
  310.     Begin
  311.         Select Top 1 @FKName = FKName From @tmpFK
  312.         Set @vchColumnasF = ''
  313.         Set @vchColumnasR = ''
  314.         While Exists ( Select * From @tmpFK Where FKName = @FKName )
  315.         Begin
  316.             Select Top 1 @ColF = ColF, @ColR = ColR, @TablaR = TablaR From @tmpFK Where FKName = @FKName
  317.             Delete From @tmpFK Where ColF = @ColF And ColR = @ColR And TablaR = @TablaR And FKName = @FKName
  318.             Set @vchColumnasF = @vchColumnasF + @ColF + ', '
  319.             Set @vchColumnasR = @vchColumnasR + @ColR + ', '
  320.         End
  321.        
  322.         Set @vchColumnasF = LEFT(@vchColumnasF, LEN(@vchColumnasF) - 1)
  323.         Set @vchColumnasR = LEFT(@vchColumnasR, LEN(@vchColumnasR) - 1)
  324.         Set @vchTemp = 'Constraint ' + @FKName + ' Foreign Key (' + @vchColumnasF + ') '
  325.         Set @vchTemp = @vchTemp + 'References ' + @TablaR + ' (' + @vchColumnasR + ')'
  326.         Set @vchForeign = @vchForeign + char(9) + @vchTemp + ',' + char(13)
  327.     End
  328.  
  329.     Select @vchResultado = Case When Len(@vchForeign) >=2 Then Left(@vchForeign, Len(@vchForeign) - 2) Else @vchForeign End
  330. End
  331. GO
  332.  
  333.  
  334. -- Genera el script del create table de una tabla dada
  335. If exists ( select * from sysobjects where name = 'sp_ppinScriptTabla' )
  336.     Drop Procedure sp_ppinScriptTabla
  337. GO
  338. create Procedure sp_ppinScriptTabla
  339. (
  340.     @vchTabla sysname
  341. )
  342. AS
  343. /* Federico Colombo */
  344. Set nocount on
  345.  
  346. Declare @table as table (Linea varchar(8000))
  347.  
  348. -- Obtengo las foreign keys
  349. Declare @foreign varchar(8000)
  350. Exec sp_ppinScriptLlavesForaneas @vchTabla, @foreign output
  351.  
  352. --Create table
  353. Insert Into @table (Linea)
  354. Select 'Create ' +
  355. Case o.xtype When 'U' Then 'Table' When 'P' Then 'Procedure' Else '??' End + ' ' +
  356. @vchTabla + char(13) + '('
  357. From sysobjects o
  358. Where o.name = @vchTabla
  359.  
  360. -- Obtengo campos
  361. Insert Into @table (Linea)
  362. Select char(9) + c.name + ' ' +                                 -- Nombre
  363. dbo.sp_ppinTipoLongitud(t.xtype, c.length, c.isnullable) +          -- Tipo(longitud)
  364. Case When c.colstat & 1 = 1                                     -- Identity (si aplica)
  365.     Then ' Identity(' + convert(varchar, ident_seed(@vchTabla)) + ',' + Convert(varchar, ident_incr(@vchTabla)) + ')'
  366.     Else ''
  367. End +
  368. Case When not od.name is null                                   -- Defaults (si aplica)
  369.     Then ' Constraint ' + od.name + ' Default ' + case when Left(cd.text, 2) = '((' And RIGHT(cd.text, 2) = '))' then SUBSTRING(cd.text, 2, LEN(cd.text) - 2) else cd.text end
  370.     Else ''
  371. End + ', '
  372. from sysobjects o, syscolumns c
  373. LEFT OUTER JOIN sysobjects od On od.id = c.cdefault LEFT OUTER join syscomments cd On cd.id = od.id,
  374. systypes t
  375. where o.id = object_id(@vchTabla)
  376. and o.id = c.id
  377. and c.xtype = t.xtype
  378. and t.xtype = t.xusertype
  379. order by c.colid
  380.  
  381.  
  382. -- Obtengo PKs y UKs
  383. Insert Into @table (Linea)
  384. select char(9) + 'Constraint ' + o.name + ' ' +
  385. Case o.xtype When 'PK' Then 'Primary Key' Else 'Unique' End + ' ' +
  386. dbo.sp_ppinCamposIndice (db_name(), @vchTabla, i.indid) + ', '
  387. from sysobjects o, sysindexes i
  388. where o.parent_obj = object_id(@vchTabla)
  389. and o.xtype in ('PK','UQ')
  390. and i.id = o.parent_obj
  391. and o.name = i.name
  392.  
  393. -- Obtengo Check constraints
  394. Insert Into @table (Linea)
  395. select char(9) + 'Constraint ' + o.name + ' Check ' + c.text + ', '
  396. from sysobjects o, syscomments c
  397. where o.parent_obj = object_id(@vchTabla)
  398. and o.xtype in ('C')
  399. and o.id = c.id
  400.  
  401. Insert Into @table (Linea)
  402. Select @foreign
  403.  
  404. Insert Into @table (Linea)
  405. Select ')'
  406.  
  407. Select Linea From @table
  408. Set nocount off
  409. GO
  410.  
  411.  
  412.  
  413.  
  414.  
  415. If exists ( Select * From sysobjects Where name = 'SP_ppinAddDrop_ForeignKeys' )
  416.     Drop procedure SP_ppinAddDrop_ForeignKeys
  417. GO
  418.  
  419. Create Procedure SP_ppinAddDrop_ForeignKeys (
  420.     @vchTabla varchar(800),
  421.     @tiTipo tinyint = 0
  422. )
  423. AS
  424. /* Federico Colombo */
  425. /*
  426. ** Nombre:                  SP_CreateDrop_ForeignKeys
  427. ** Propósito:              Genera automáticamente un script con los alter table (drop o add) de los constraints
  428. **                      que hacen referencia (foránea) a la tabla especificada
  429. ** Parámetros:             @vchTabla       Tabla a la que HACEN referencia los constraints
  430. **                      @tiTipo     0: Hace el ADD
  431. **                                  1: Hace el DROP
  432. **
  433. ** Dependencias:               
  434. **
  435. ** Fecha creación:         23/11/2005
  436. ** Autor creación:         FDCG
  437. ** csd creación:          
  438. ** Fecha modificación:
  439. ** Autor modificacion:
  440. ** csd modificación:
  441. ** Compatibilidad:          1.75
  442. ** Revision:                1
  443. */
  444. Set nocount on
  445. Create Table #tempConstraints       --Tabla que contiene todos los IDs de los constraints (FK) que referencian a algún campo de @vchTabla
  446. (
  447.     constid int not null,
  448.     tiUsado tinyint not null
  449. )
  450.  
  451. Create Table #tempColumnas      --Tabla que contiene (una vez por cada constID) las tabla y los campos a los que referencia
  452. (
  453.     TablaDesde sysname not null,
  454.     TablaHasta sysname not null,
  455.     ColumnaDesde sysname not null,
  456.     ColumnaHasta sysname not null,
  457.     tiUsado tinyint not null
  458. )
  459.  
  460. --Declare @vchTabla varchar(200)
  461. --Set @vchTabla = 'ACFDEPE1'
  462.  
  463. Declare @constid int, @vchCreate varchar(4000), @vchDrop varchar(1000)
  464. Declare @TablaF varchar(100), @TablaR varchar(100)
  465. Declare @ColF varchar(100), @ColR varchar(100)
  466. Declare @CamposIzquierda varchar(500), @CamposDerecha varchar(500)
  467.  
  468. -- Lleno la temporal de constraints
  469. Insert #tempConstraints
  470. Select r.constid, 0
  471. from sysreferences r, sysobjects o
  472. where o.name = @vchTabla
  473. And rkeyid = o.id
  474. order by 1
  475.  
  476. If not exists (select * from #tempConstraints)
  477.     If object_id(@vchTabla) Is Null
  478.         Print 'La tabla [' + @vchTabla + '] no existe en [' + db_name() + ']'
  479.     Else
  480.         Print 'La tabla [' + @vchTabla + '] no tiene referencias foráneas'
  481. Else
  482.     While exists (Select * From #tempConstraints Where tiUsado = 0)
  483.     Begin
  484.         Select Top 1 @constid = constid From #tempConstraints Where tiUsado = 0
  485.    
  486.         Set @CamposIzquierda = ''
  487.         Set @CamposDerecha = ''
  488.         Set @vchCreate = ''
  489.         Set @vchDrop = ''
  490.    
  491.         -- Lleno la temporal de columnas   
  492.         Insert #tempColumnas (TablaDesde, TablaHasta,  ColumnaDesde, ColumnaHasta, tiUsado)
  493.         Select TablaF.name, TablaR.name, ColF.name, ColR.name, 0
  494.         From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR,
  495.         syscolumns ColF, syscolumns ColR
  496.         Where ofk.name = object_name(@constid)
  497.         And ofk.id = fk.constid
  498.         And TablaF.id = fk.fkeyid
  499.         And TablaR.id = fk.rkeyid
  500.         And ColF.id = TablaF.id And ColF.colid = fk.fkey
  501.         And ColR.id = TablaR.id And ColR.colid = fk.rkey
  502.  
  503. --      Select * from #tempColumnas
  504.  
  505.         While Exists (Select * From #tempColumnas Where tiUsado = 0)
  506.         Begin
  507.             Select Top 1 @ColF = ColumnaDesde, @ColR = ColumnaHasta
  508.             From #tempColumnas
  509.             Where tiUsado = 0
  510.            
  511.             Set @CamposIzquierda = @CamposIzquierda + @ColF + ', '
  512.             Set @CamposDerecha = @CamposDerecha + @ColR + ', '
  513.        
  514.             Update #tempColumnas
  515.             Set tiUsado = 1
  516.             Where ColumnaDesde = @ColF And ColumnaHasta = @ColR
  517.         End
  518.  
  519.         Set @CamposIzquierda = LEFT(@CamposIzquierda, LEN(@CamposIzquierda) - 1)
  520.         Set @CamposDerecha = LEFT(@CamposDerecha, LEN(@CamposDerecha) - 1)
  521.  
  522.         Select Top 1 @TablaF = TablaDesde, @TablaR = TablaHasta From #tempColumnas
  523.  
  524.         Set @vchCreate = 'If Not Exists (Select * From SysObjects Where Name = ''' + object_name(@constid) + ''') '
  525.         Set @vchCreate = @vchCreate + 'And object_id(''' + @TablaF + ''') is not null ' + char(13)
  526.         Set @vchCreate = @vchCreate + char(9) + 'Alter Table ' + @TablaF + char(13)
  527.         Set @vchCreate = @vchCreate + char(9) + char(9) + 'Add Constraint ' + object_name(@constid) + ' Foreign Key' + char(13)
  528.         Set @vchCreate = @vchCreate + char(9) + char(9) + '(' + @CamposIzquierda + ') '
  529.         Set @vchCreate = @vchCreate + 'References ' + @TablaR
  530.         Set @vchCreate = @vchCreate + ' (' + @CamposDerecha + ')'
  531.    
  532.         Set @vchDrop = 'If Exists (Select * From SysObjects Where Name = ''' + object_name(@constid) + ''') ' + char(13)
  533.         Set @vchDrop = @vchDrop + char(9) + 'Alter Table ' + @TablaF + char(13)
  534.         Set @vchDrop = @vchDrop + char(9) + char(9) + 'Drop Constraint ' + object_name(@constid)
  535.  
  536.         If @tiTipo = 1
  537.             Print @vchDrop
  538.         else
  539.             Print @vchCreate           
  540.  
  541.         Update #tempConstraints
  542.         Set tiUsado = 1
  543.         Where constid = @constid
  544.    
  545.         Delete #tempColumnas
  546.         Where tiUsado = 1
  547.     End
  548.  
  549. Set nocount off
  550. GO
  551.  
  552.  
  553.  
  554. If exists ( Select * From sysobjects Where name = 'SP_ppinGenera_Insert' )
  555.     Drop procedure SP_ppinGenera_Insert
  556. GO
  557.  
  558. Create Procedure SP_ppinGenera_Insert (
  559.     @vchTabla varchar(200),
  560.     @vchWhere varchar(8000) = '',
  561.     @tiTipo tinyint = 0,
  562.     @tiTipoResultado tinyint = 0
  563. )
  564. AS
  565. /* Federico Colombo */
  566. /*
  567. ** Nombre:                  sp_Genera_Insert
  568. ** Propósito:              Genera el script que inserta los datos de una tabla
  569. ** Parámetros:             @vchTabla   Nombre de la tabla
  570. **                      @vchWhere   (opcional) filtro para el where
  571. **                      @tiTipo 0: Genera el if exists DELETE->INSERT
  572. **                              1: Genera el if not exists INSERT
  573. **                              2: Genera el if exists UPDATE else INSERT
  574. **                      @tiTipoResultado Tipo de resultado
  575. **                              0:  El resultado se arroja con prints, se informa al usuario en caso de errores o llaves primarias
  576. **                              1:  El resultado se arrojo con select para que se posible atrapar el resultado en insert a alguna tabla
  577. **                                      el resultado siempre tendra un unico campo, se eliminan los mensajes informativos
  578. **
  579. ** Dependencias:               
  580. **
  581. ** Fecha creación:         23/11/05
  582. ** Autor creación:         FDCG
  583. */
  584.  
  585. Set Nocount On
  586.  
  587. Declare @tiEsCampoText tinyint
  588. Declare @vchBaseDatos varchar(100)
  589. Declare @vchBaseDatosConPunto varchar(100)
  590. Declare @vchBaseDatosConTabla varchar(100)
  591. Declare @iPosicionNombreTabla int
  592. Declare @nvchQuery nvarchar(4000)
  593. Declare @nvchParametros nvarchar(512)
  594. Declare @iCantRegistro int
  595. Declare @vchBaseDatosActual varchar(100)
  596. Declare @Enter char(2)
  597. Declare @vchEnter nvarchar(20)
  598. Declare @tiLlavePrimaria tinyint
  599. Select @vchBaseDatosActual = db_name()
  600. Select @Enter = char(13) + char(10)
  601. Set @vchEnter = 'char(13) + char(10)' --Donde se quiere que el script retornado haga enter's
  602. create table #tmpIndex
  603. (
  604.     TABLE_QUALIFIER sysname NOT NULL,
  605.     TABLE_OWNER     sysname NOT NULL,
  606.     TABLE_NAME      sysname NOT NULL,
  607.     COLUMN_NAME     sysname NOT NULL,
  608.     KEY_SEQ     smallint NOT NULL,
  609.     PK_NAME     sysname  NOT NULL
  610. )
  611.  
  612. Create Table #Campos
  613. (
  614.     vchNombre varchar(60) not null,     -- Nombre de la columna
  615.     tiLlavePrimaria tinyint not null,       -- Indica si es llave primaria
  616.     tiEsCadena tinyint not null,            -- Indica si el campo es una cadena (varchar, nvarchar, etc)
  617.     tiUsado tinyint not null,           -- Campo para hacer ciclos while
  618.     tiEsTimeStamp tinyint not null,     -- Indica si es del tipo TimeStamp (para poner la palabra NULL en el values)
  619.     tiAdmiteNulos tinyint not null,     -- Indica si el campo admite nulos
  620.     tiEsFecha tinyint not null,
  621.     tiEsCampoText tinyint not null --Indica que es un campo tipo text, para no utilizar el replace
  622.  
  623. )
  624. Create table #tmpTexto
  625. (
  626.     vchTexto varchar(8000)
  627. )
  628.  
  629. --Revisar si en el nombre de la table trae concatenada la base de datos
  630. If @vchTabla like '%..%'
  631. Begin
  632.     Select @vchBaseDatosConTabla= @vchTabla,
  633.             @iPosicionNombreTabla = PATINDEX('%..%', @vchTabla)
  634.  
  635.     Select @vchBaseDatosConPunto = substring( @vchBaseDatosConTabla, 1 , @iPosicionNombreTabla + 1) --Base de datos con puntos
  636.     Select @vchBaseDatos = substring( @vchBaseDatosConTabla, 1 , @iPosicionNombreTabla - 1)
  637.    
  638.     Select @vchTabla = substring( @vchBaseDatosConTabla, @iPosicionNombreTabla + 2, 200)
  639. End
  640. Else
  641. Begin
  642.     Set @vchBaseDatosConTabla = @vchTabla
  643.     Set @vchBaseDatos = ''
  644.     Set @vchBaseDatosConPunto = ''
  645. End
  646.  
  647. Set @nvchQuery = N'Select @iCantRegistro = count(*) From ' + @vchBaseDatosConPunto + 'sysobjects o '
  648. Set @nvchQuery = @nvchQuery + N'Where o.name = ''' + @vchTabla + ''' and xtype = ''' + 'u' + ''''
  649.  
  650. Set @nvchParametros = N'@iCantRegistro int output '
  651. Exec sp_executesql @nvchQuery, @nvchParametros, @iCantRegistro = @iCantRegistro output
  652.  
  653. If @iCantRegistro <= 0
  654. Begin
  655.     if @tiTipoResultado = 0
  656.     Begin
  657.         Print 'La tabla ' + @vchTabla + ' no existe'
  658.     End
  659.     Goto Fin
  660. End
  661.  
  662.  
  663. If @vchBaseDatosActual <> @vchBaseDatos And @vchBaseDatos <> ''
  664. Begin
  665.     Set @nvchQuery = N'' + @vchBaseDatosConPunto
  666.     Set @nvchQuery = @nvchQuery + N'sp_pkeys ''' + @vchTabla + ''''
  667.  
  668.     Insert into #tmpIndex
  669.     Exec (@nvchQuery)
  670. End
  671. Else
  672. Begin
  673.     Insert into #tmpIndex
  674.     Exec ('sp_pkeys ''' + @vchTabla + '''')
  675. End
  676.  
  677.  
  678. --Inserto todos los campos de la tabla en la temporal
  679. Set @nvchQuery = N'Select c.name, 0, ' + @Enter
  680. Set @nvchQuery = @nvchQuery + N'Case When c.xtype IN ( 35, 36, 98, 99, 240, 165, 167, 173, 175, 231, 239, 241, 231 ) Then ' + @Enter --35->(ntext, text), 47->(char, nchar), 39(nvarchar, varchar, sysname, sql_variant)
  681. Set @nvchQuery = @nvchQuery + N'    1 Else 0 End, ' + @Enter
  682. Set @nvchQuery = @nvchQuery + N'0, Case When c.xtype = 189 Then 1 Else 0 End, ' + @Enter
  683. Set @nvchQuery = @nvchQuery + N'c.isnullable, ' + @Enter
  684. Set @nvchQuery = @nvchQuery + N'Case When c.xtype IN ( 40, 41, 42, 58, 61 ) Then 1 Else 0 End, ' + @Enter -- date, time, datetime2, smalldatetime, datetime
  685. Set @nvchQuery = @nvchQuery + N'Case When c.xtype IN ( 35, 99, 241 ) Then ' + @Enter -- (ntext, text, xml)
  686. Set @nvchQuery = @nvchQuery + N'    1 Else 0 End ' + @Enter
  687. Set @nvchQuery = @nvchQuery + N'From ' + @vchBaseDatosConPunto + 'sysobjects o, ' + @vchBaseDatosConPunto + 'syscolumns c ' + @Enter
  688. Set @nvchQuery = @nvchQuery + N'Where o.id = c.id ' + @Enter
  689. Set @nvchQuery = @nvchQuery + N'And o.name = ''' + @vchTabla + ''' ' + @Enter
  690. Set @nvchQuery = @nvchQuery + N'And c.name not in (''CreatedDate'', ''CreatedBy'', ''LastUpdatedDate'', ''LastUpdatedBy'') '
  691. Set @nvchQuery = @nvchQuery + N'And o.type = ''U''' + @Enter
  692. Set @nvchQuery = @nvchQuery + N'Order by c.colid ' + @Enter
  693. --Select @nvchQuery as nvchQuery
  694.  
  695. Insert #Campos (vchNombre, tiLlavePrimaria,
  696. tiEsCadena,
  697. tiUsado, tiEsTimeStamp,
  698. tiAdmiteNulos,
  699. tiEsFecha,
  700. tiEsCampoText )
  701. execute (@nvchQuery)
  702.  
  703. --Actualizo el valor de tiLlavePrimaria, para los que pertenecen al PK
  704. Update #Campos
  705. Set tiLlavePrimaria = 1
  706. From #tmpIndex tmp
  707. Where tmp.COLUMN_NAME = vchNombre
  708.  
  709. Declare @vchReturn varchar(8000), @vchWhere1 varchar(1000), @vchInsert varchar(1000), @vchValues varchar(8000)
  710. Declare @vchCamposComa varchar(1000)
  711.  
  712. Declare @vchUpdate1 varchar(8000), @vchUpdate2 varchar(8000), @vchTemp varchar(8000)
  713. Declare @esFecha tinyint
  714. Select @vchUpdate1 = '', @vchUpdate2 = ''
  715.  
  716.  
  717. Declare @Columna nvarchar(128), @esCadena tinyint, @tiEsTimeStamp tinyint
  718. Set @vchReturn = ''
  719. Set @vchCamposComa = ''
  720.  
  721. If not exists (Select * from #tmpIndex)
  722. -- No hay ninguna llave primaria, las marco a todas como primarias (las que no aceptan nulos y son distintas de timestamp
  723. Begin
  724.     if @tiTipoResultado = 0
  725.     Begin
  726.         Print 'Tabla sin llave primaria, se usarán como llave primaria todos los campos que no admitan nulos' + @Enter + @Enter
  727.     End
  728.     Update #Campos
  729.     Set tiLlavePrimaria = 1
  730.     Where tiLlavePrimaria = 0 And tiAdmiteNulos = 0 And tiEsTimeStamp = 0
  731. End
  732.  
  733. -- Actualizo [nombre]
  734. Update #Campos
  735. Set vchNombre = '[' + vchNombre + ']'
  736.  
  737. -- Muestro la llave primaria
  738. While exists (Select * From #Campos Where tiUsado = 0 And tiLlavePrimaria = 1)
  739. Begin
  740.     Select Top 1 @Columna = vchNombre From #Campos Where tiUsado = 0 And tiLlavePrimaria = 1
  741.    
  742.     Set @vchReturn = @vchReturn + @Columna + ', '
  743.  
  744.     Update #Campos
  745.     Set tiUsado = 1
  746.     Where vchNombre = @Columna
  747.     And tiLlavePrimaria = 1
  748. End
  749. Set @vchReturn = LEFT(@vchReturn, LEN(@vchReturn) - 1)  --Quito la última coma
  750. if @tiTipoResultado = 0
  751. Begin
  752.     Print 'Llave primaria de la tabla [' + @vchTabla + ']: ' + @vchReturn
  753. End
  754.  
  755. Set @vchReturn = ''
  756. Update #Campos
  757. Set tiUsado = 0
  758.  
  759. ----------LLENO EL WHERE
  760. Set @vchWhere1 = 'Where '
  761. While exists (Select * from #Campos where tiLlavePrimaria = 1 And tiUsado = 0 And tiEsTimeStamp = 0)
  762. Begin
  763.     Select Top 1 @Columna = vchNombre, @esCadena = tiEsCadena, @tiEsCampoText = tiEsCampoText
  764.     From #Campos where tiLlavePrimaria = 1 And tiUsado = 0 And tiEsTimeStamp = 0
  765.  
  766.     Set @vchWhere1 = @vchWhere1 + @Columna + ' = '
  767.     If @esCadena = 1
  768.         -- Hay que poner comillas
  769.         Begin
  770.             If @tiEsCampoText = 1
  771.             Begin
  772.                 Set @vchWhere1 = @vchWhere1 + ''''''' + ' + @Enter + 'Convert(nvarchar(max), '+ @Columna + ') + '''''' '
  773.             End
  774.             Else
  775.             Begin
  776.                 Set @vchWhere1 = @vchWhere1 + ''''''' + ' + @Enter + 'Convert(nvarchar(max), Replace(' + @Columna + ', '''''''', '''''''''''')) + '''''' '
  777.             End
  778.  
  779.             Set @vchWhere1 = @vchWhere1 + ' AND '      
  780.         End
  781.     Else
  782.         -- Sin comillas
  783.         Begin
  784.             --Set @vchWhere1 = @vchWhere1 + ''' + Convert(VarChar(8000),' + @Columna + ') + '
  785.             Set @vchWhere1 = @vchWhere1 + ''' + ' + @Enter + 'Convert(nvarchar(max),' + @Columna + ') + '
  786.             Set @vchWhere1 = @vchWhere1 + ''' AND '
  787.         End
  788.  
  789.     Update #Campos
  790.     Set tiUsado = 1
  791.     Where vchNombre = @Columna
  792. End
  793.  
  794. -- Quito el último AND
  795. If @esCadena = 1        --Si el último fue cadena
  796.     Set @vchWhere1 = LEFT(@vchWhere1, LEN(@vchWhere1) - 5) + ''''
  797. Else
  798.     Set @vchWhere1 = LEFT(@vchWhere1, LEN(@vchWhere1) - 7)
  799.  
  800. -------------- LLENO EL INSERT
  801. -- Lleno la variable @vchCamposComa con los campos de la tabla separados por coma
  802. Update #Campos
  803. Set tiUsado = 0
  804. While exists (Select * from #Campos Where tiUsado = 0)
  805. Begin
  806.     Select Top 1 @Columna = vchNombre
  807.     From #Campos
  808.     Where tiUsado = 0
  809.  
  810.     Set @vchCamposComa = @vchCamposComa + @Columna + ', '
  811.  
  812.     Update #Campos
  813.     Set tiUsado = 1
  814.     Where vchNombre = @Columna
  815. End
  816. --Quito la última coma
  817. Set @vchCamposComa = LEFT(@vchCamposComa, LEN(@vchCamposComa) - LEN(', '))
  818.  
  819. Set @vchInsert = 'Insert Into ' + @vchTabla + '(' + @vchCamposComa + ')'
  820.  
  821. -------------- LLENO EL VALUES
  822. Update #Campos
  823. Set tiUsado = 0
  824. Set @vchValues = 'Values ('''
  825. While exists (Select * from #Campos Where tiUsado = 0)
  826. Begin
  827.     Select Top 1 @Columna = vchNombre, @esCadena = tiEsCadena, @tiEsTimeStamp = tiEsTimeStamp, @esFecha = tiEsFecha,
  828.     @tiEsCampoText = tiEsCampoText, @tiLlavePrimaria = tiLlavePrimaria
  829.     From #Campos
  830.     Where tiUsado = 0
  831.  
  832.     If @esCadena = 1 Or @esFecha = 1
  833.     Begin
  834.         --Poner comillas
  835.         Begin
  836.             If @tiEsCampoText = 1
  837.             Begin
  838.                 Set @vchTemp = ' + ' + @Enter + 'Case When ' + @Columna + ' Is Null Then ''Null'' Else ''N'''''' + Convert(nvarchar(max), ' + @Columna + ') + '''''''' End + '', '''
  839.             End
  840.             Else --No campo tipo text
  841.             Begin
  842.                 Set @vchTemp = ' + ' + @Enter + 'Case When ' + @Columna + ' Is Null Then ''Null'' Else ''N'''''' + Convert(nvarchar(max), Replace(' + @Columna + ','''''''','''''''''''')) + '''''''' End + '', '''
  843.             End
  844.             Set @vchValues = @vchValues + @vchTemp
  845.         End
  846.     End
  847.     Else
  848.     Begin
  849.         If @tiEsTimeStamp = 1
  850.         Begin
  851.             Set @vchTemp = ' + ' + @Enter + '''Null'' + '', '''
  852.             Set @vchValues = @vchValues + @vchTemp
  853.             -- De los timestamps no hago update
  854.         End
  855.         Else
  856.         Begin
  857.             Set @vchTemp = ' + ' + @Enter + 'Case When ' + @Columna + ' Is Null Then ''Null'' Else Convert(nvarchar(max), ' + @Columna + ') End + '', '''
  858.             Set @vchValues = @vchValues + @vchTemp
  859.         End
  860.     End
  861.    
  862.     -- If es la ultima columna, qutar la coma del final
  863.     if ( Select count(1) from #Campos Where tiUsado = 0 ) = 1
  864.     Begin
  865.         Set @vchTemp = LEFT(@vchTemp, LEN(@vchTemp) - 6)
  866.     End
  867.    
  868.     -- Armar el update
  869.     If @tiLlavePrimaria = 0
  870.     Begin
  871.         If len(@vchUpdate1) + len(@vchTemp) <= 7500
  872.         Begin
  873.             Set @vchUpdate1 = @vchUpdate1 + '''' + @Columna + ' = ''' + @vchTemp + ' + ' + @vchEnter + ' + char(9) + '
  874.         End
  875.         Else
  876.         Begin
  877.             Set @vchUpdate2 = @vchUpdate2 + '''' + @Columna + ' = ''' + @vchTemp + ' + ' + @vchEnter + ' + char(9) + '
  878.         End
  879.     End
  880.    
  881.     Update #Campos
  882.     Set tiUsado = 1
  883.     Where vchNombre = @Columna
  884. End
  885.  
  886. --Quito la última coma
  887. If @esCadena = 1
  888. Begin
  889.     Set @vchValues = LEFT(@vchValues, LEN(@vchValues) - 6) + '+ '')'''      -- 8
  890.     If len(@vchUpdate1) + len(@vchTemp) <= 7500
  891.     Begin
  892.         Set @vchUpdate1 = LEFT(@vchUpdate1, LEN(@vchUpdate1) - 34)
  893.     End
  894.     Else
  895.     Begin
  896.         Set @vchUpdate2 = LEFT(@vchUpdate2, LEN(@vchUpdate2) - 34)
  897.     End
  898. End
  899. Else
  900.     If @tiEsTimeStamp = 1
  901.     Begin
  902.         Set @vchValues = LEFT(@vchValues, LEN(@vchValues) - 3) + ')'''     
  903.     End
  904.     Else
  905.     Begin
  906.         Set @vchValues = LEFT(@vchValues, LEN(@vchValues) - 6) + '+ '')'''
  907.         If len(@vchUpdate1) + len(@vchTemp) <= 7500
  908.         Begin
  909.             Set @vchUpdate1 = LEFT(@vchUpdate1, LEN(@vchUpdate1) - 34)  
  910.         End
  911.         Else
  912.         Begin
  913.             select len(@vchUpdate1), LEN(@vchUpdate2)
  914.             Set @vchUpdate2 = LEFT(@vchUpdate2, LEN(@vchUpdate2) - 34)  
  915.         End
  916.     End
  917.  
  918. --FINAL
  919. if @tiTipo = 0          -- Generar el if exists->delete->Insert
  920.     Begin
  921.         Set @vchReturn = 'Select ''If Exists (Select * From ' + @vchTabla + ' ' + @vchWhere1 + '+ '')'' + ' + @vchEnter + ' + Char(9) + ' + @Enter + '''Delete ' + @vchTabla
  922.         Set @vchReturn = @vchReturn + ' ' + @vchWhere1 + ' + ' + @Enter + '' + @vchEnter + ' + ''GO'' + ' + @vchEnter + ' + '
  923.         Set @vchReturn = @vchReturn + @Enter + '''' + @vchInsert + ''' + ' + @vchEnter + ' + ' + @Enter + '''' + @vchValues + ' + ' + @Enter + '' + @vchEnter + ' + ''GO'' + ' + @vchEnter + ' ' + @Enter + 'From ' + @vchBaseDatosConPunto + @vchTabla
  924.     End
  925. else if @tiTipo = 1     -- Generar el if not exists->Insert
  926.     Begin
  927.         Set @vchReturn = 'Select ''If Not Exists (Select * From ' + @vchTabla + ' ' + @vchWhere1 + '+ '')'' + Char(9) + ' + @Enter
  928.         Set @vchReturn = @vchReturn + ' + ' + @vchEnter + ' + char(9) + '
  929.         Set @vchReturn = @vchReturn + @Enter + '''' + @vchInsert + ''' + ' + @vchEnter + ' + char(9) + ' + @Enter + '''' + @vchValues + ' + ' + @Enter + '' + @vchEnter + ' + ''GO'' + ' + @vchEnter + ' ' + @Enter + 'From ' + @vchBaseDatosConPunto + @vchTabla
  930.     End
  931. else if @tiTipo = 2     -- Generar el if exists Insert else Update
  932.     Begin
  933.         -- En este caso, no alcanzan los 8000 caracteres que permite el query analizer como respuesta de un select, entonces hago prints parciales
  934.         if @tiTipoResultado = 0 --resultado con prints
  935.         Begin
  936.             Print ''
  937.             Print 'Select ''If Exists (Select * From ' + @vchTabla + ' ' + @vchWhere1 + '+ '')'' + ' + @vchEnter + ' + Char(9) + '
  938.             Print '''Update ' + @vchTabla + @Enter + char(9) + 'Set ' + ''' + '
  939.             Print @vchUpdate1
  940.             Print @vchUpdate2 + ' + ' + @vchEnter + ' + char(9) + ''' + @vchWhere1
  941.             Print ' + ' + @vchEnter + ' + ''Else'' + ''' + @Enter + char(9) + @vchInsert + ''' + ' + @vchEnter + ' + char(9) + ''' + @vchValues
  942.             Print ' + ' + @Enter + '' + @vchEnter + ' + ''GO'' + ' + @vchEnter + ' + ' + @vchEnter + ' ' + @Enter + 'From ' + @vchBaseDatosConPunto + @vchTabla
  943.             If @vchWhere <> ''
  944.                 Print 'Where ' + @vchWhere
  945.         End
  946.         Else if @tiTipoResultado = 1 --resultado con selects
  947.         Begin
  948.             Insert into #tmpTexto
  949.             Select ''
  950.  
  951.             Insert into #tmpTexto
  952.             Select 'Select ''If Exists (Select * From ' + @vchTabla + ' ' + @vchWhere1 + '+ '')'' + ' + @vchEnter + ' + Char(9) + '
  953.  
  954.             Insert into #tmpTexto
  955.             Select '''Update ' + @vchTabla + @Enter + char(9) + 'Set ' + ''' + '
  956.  
  957.             Insert into #tmpTexto
  958.             Select @vchUpdate1  + @Enter
  959.  
  960.             Insert into #tmpTexto
  961.             Select @vchUpdate2 + ' + ' + @vchEnter + ' + char(9) + ''' + @vchWhere1
  962.            
  963.             Insert into #tmpTexto
  964.             Select ' + ' + @vchEnter + ' + ''Else'' + ''' + @Enter + char(9) + @vchInsert + ''' + ' + @vchEnter + ' + char(9) + ''' + @vchValues
  965.  
  966.             Insert into #tmpTexto
  967.             Select ' + ' + @Enter + '' + @vchEnter + ' + ''GO'' + ' + @vchEnter + ' + ' + @vchEnter + ' ' + @Enter + 'From ' + @vchBaseDatosConPunto + @vchTabla
  968.  
  969.             If @vchWhere <> ''
  970.             Begin
  971.                 Insert into #tmpTexto
  972.                 Select 'Where ' + @vchWhere + @Enter
  973.             End
  974.  
  975.             Select *
  976.             From #tmpTexto
  977.         End
  978.     End
  979.  
  980. If @vchWhere <> ''
  981.     Set @vchReturn = @vchReturn + @Enter + 'Where ' + @vchWhere
  982.  
  983. if @tiTipo <> 2
  984.     if @tiTipoResultado = 0 --resultado con prints
  985.     Begin
  986.         Print @vchReturn
  987.     End
  988.     Else if @tiTipoResultado = 1 --resultado con selects
  989.     Begin
  990.         Insert into #tmpTexto
  991.         Select @vchReturn
  992.  
  993.         Select * from #tmpTexto
  994.     End
  995. Fin:
  996. Set Nocount Off
  997. GO
  998.  
  999. If exists ( Select * From sysobjects Where name = 'sp_longitud' )
  1000.     Drop procedure sp_longitud
  1001. GO
  1002.  
  1003. Create procedure sp_longitud(
  1004. @vchValor varchar(8000)
  1005. )
  1006. AS
  1007. Print len(@vchValor)
  1008. GO
  1009.  
  1010. If exists ( Select * From sysobjects Where name = 'sp_doc_comment' )
  1011.     Drop procedure sp_doc_comment
  1012. GO
  1013.  
  1014. Create procedure sp_doc_comment
  1015. AS
  1016. Begin
  1017.     Declare @now nvarchar(25) = convert(nvarchar, GetDate(), 103), @user nvarchar(100) = SYSTEM_USER
  1018.     Set @user = SUBSTRING(@user, CHARINDEX('\', @user) + 1, 100)
  1019.  
  1020.     Print '/*'
  1021.     Print '** Name:         '
  1022.     Print '** Purpose:      '      
  1023.     Print '** Parameters:   '              
  1024.     Print '** Dependencies: '              
  1025.     Print '** Errors:       '          
  1026.     Print '** Usage sample: '          
  1027.     Print '** Return:       '
  1028.     Print '**   '
  1029.     Print '** Creation Date: ' + @now
  1030.     Print '** Creation User: ' + @user
  1031.     Print '** Revision:      0'
  1032.     Print '** '
  1033.     Print '** Changes history'
  1034.     Print '** ------------------------------------------------------------------'
  1035.     Print '** Date        User             Description'
  1036.     Print '**'
  1037.     Print '*/'
  1038. End
  1039. GO
  1040.  
  1041.  
  1042.  
  1043. If exists ( Select * From sysobjects Where name = 'sp_drop' )
  1044.     Drop procedure sp_drop
  1045. GO
  1046.  
  1047. Create procedure sp_drop(
  1048. @objeto varchar(100)
  1049. )
  1050. AS
  1051. Declare @tipoObjeto char(2), @vchCommand varchar(500)
  1052.  
  1053. If Substring(@objeto, 1, 1) = '#'
  1054. Begin
  1055.     -- Posible temporal, intento hacer el drop sin más
  1056.     Set @vchCommand = 'DROP TABLE ' + @objeto
  1057.     EXECUTE (@vchCommand)
  1058.     If @@error = 0
  1059.         Print @objeto + ' Eliminado'
  1060.     Return 0
  1061. End
  1062.  
  1063. Set @vchCommand = ''
  1064. Select @tipoObjeto = o.type From SysObjects o Where Name = @objeto
  1065. If @tipoObjeto IS NULL
  1066. BEGIN
  1067.     If object_id(@objeto) Is Null
  1068.         Print 'El objeto [' + @objeto + '] no existe en [' + db_name() + ']'
  1069.     else
  1070.         Print 'El objeto [' + @objeto + '] no es un objeto válido'
  1071.     Return -1
  1072. END
  1073.  
  1074. If @tipoObjeto = 'P' OR @tipoObjeto = 'X'   -- Store Procedure
  1075.         Set @vchCommand = @vchCommand + 'DROP PROCEDURE ' + @objeto
  1076. If @tipoObjeto = 'U'                -- Tabla
  1077.         Set @vchCommand = @vchCommand + 'DROP TABLE ' + @objeto
  1078.  
  1079. EXECUTE (@vchCommand)
  1080. If @@error = 0
  1081.     Print @objeto + ' Eliminado'
  1082. Return 0
  1083. GO
  1084.  
  1085.  
  1086.  
  1087. If exists ( Select * From sysobjects Where name = 'sp_ppinNombreTablaTemp' )
  1088.     Drop procedure sp_ppinNombreTablaTemp
  1089. GO
  1090.  
  1091. Create Procedure sp_ppinNombreTablaTemp
  1092. (
  1093.     @vchTabla varchar(512)
  1094. )
  1095. AS
  1096. /*
  1097. ** Nombre:              sp_ppinNombreTablaTemp
  1098. ** Propósito:              Dado un nombre de tabla temporal (ej. #tmp) devuelve el nombre real de la tabla en tempdb
  1099. ** Campos/Parámetros:      @vchTabla           Nombre de la tabla
  1100. **
  1101. ** Dependencias:            ?
  1102. **
  1103. ** Fecha creación:         03-01-06
  1104. ** Autor creación:         FDCG
  1105. */
  1106. Declare @vchReal varchar(512)
  1107. If LEFT(@vchTabla, 1) <> '#'
  1108.     Begin
  1109.         Print @vchTabla
  1110.         Return
  1111.     End
  1112. Select @vchReal = convert(varchar(512),name) From tempdb..sysobjects where name like @vchTabla + '_%'
  1113. Print @vchReal
  1114. GO
  1115.  
  1116.  
  1117. -- SP que dada una tabla, devuelve un SELECT de la misma con las cláusula From y Where según sus llaves foráneas
  1118. If exists ( Select * From sysobjects Where name = 'sp_ppinSelectFromWhereForaneo' )
  1119.     Drop procedure sp_ppinSelectFromWhereForaneo
  1120. GO
  1121.  
  1122. Create Procedure sp_ppinSelectFromWhereForaneo
  1123. (
  1124.     @vchTabla varchar(100),
  1125.     @vchAliasTabla varchar(5) = 'A'
  1126. )
  1127. AS
  1128. /*
  1129. ** Nombre:                  sp_ppinSelectFromWhereForaneo
  1130. ** Propósito:                  SP que genera un Select * a partir de una tabla.
  1131. **                          El select se genera con el From y el Where según las llaves foráneas de la tabla
  1132. ** Campos:                  @vchTabla: Tabla a la que se hará el select
  1133. **                          @vchAliasTabla: Alias que tendrá la tabla en el select
  1134. ** Dependencias:               
  1135. **                                             
  1136. ** Fecha creación:             17/Mayo/2007
  1137. ** Autor creación:             FDCG
  1138. ** Csd creación:               csd171
  1139. ** Fecha modificación:    
  1140. ** Autor modificación:    
  1141. ** Csd modificación:          
  1142. ** Compatibilidad:              1.75
  1143. ** Revisión:                   0
  1144. */
  1145. Set nocount On
  1146. Declare @TablaR sysname, @ColF sysname, @ColR sysname, @vchAlias varchar(5)
  1147. Declare @vchFrom varchar(4000), @vchWhere varchar(4000), @iCont int, @iHayMas int
  1148.  
  1149. If not exists ( Select * From sysobjects where name = @vchTabla And xtype in ('U') )
  1150. Begin
  1151.     Set nocount Off
  1152.     Print 'La tabla ' + @vchTabla + ' no existe en [' + db_name() + ']'
  1153.     Return
  1154. End
  1155.  
  1156. If exists ( Select * From tempdb..sysobjects Where name like '#tmpForeign[_]%' )
  1157.     Drop table #tmpForeign
  1158.  
  1159. Create Table #tmpForeign
  1160. (
  1161.     iIdentity int not null identity (1,1),
  1162.     TablaF sysname,
  1163.     TablaR sysname,
  1164.     ColF sysname,
  1165.     ColR sysname,
  1166.     FKName sysname,
  1167.     vchAlias varchar(5),
  1168.     tiProceso tinyint
  1169. )
  1170.  
  1171. Insert Into #tmpForeign (TablaF, TablaR, ColF, ColR, FKName,
  1172. vchAlias, tiProceso)
  1173. Select TablaF.name, TablaR.name, ColF.name, ColR.name, ofk.name,
  1174. substring(TablaR.name, 1, 1) + substring(TablaR.name, 4, 1) , 0
  1175. From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR,
  1176. syscolumns ColF, syscolumns ColR
  1177. Where TablaF.name = @vchTabla
  1178. And ofk.id = fk.constid
  1179. And TablaF.id = fk.fkeyid
  1180. And TablaR.id = fk.rkeyid
  1181. And ColF.id = TablaF.id And ColF.colid = fk.fkey
  1182. And ColR.id = TablaR.id And ColR.colid = fk.rkey
  1183. order by Left(TablaR.name, 2)
  1184.  
  1185. Update t
  1186. Set vchAlias = Upper(vchAlias) + Cast(iIdentity As varchar)
  1187. From #tmpForeign t
  1188.  
  1189.  
  1190. If exists ( Select * From #tmpForeign Where tiProceso = 0 )
  1191. Begin
  1192.     Set @vchFrom = 'From ' + @vchTabla + ' ' + @vchAliasTabla + ', '
  1193.     Set @vchWhere = 'Where '
  1194. End
  1195. Else
  1196. Begin
  1197.     Print 'La tabla ' + @vchTabla + ' no tiene llaves foráneas'
  1198.     Return
  1199. End
  1200.  
  1201. Set @iCont = 0
  1202. While exists ( Select * From #tmpForeign Where tiProceso = 0 )
  1203. Begin
  1204.     Set @iCont = @iCont + 1
  1205.     Set @iHayMas = Case When (Select count(*) From #tmpForeign Where tiProceso = 0) > 1 Then 1 Else 0 End
  1206.  
  1207.     Select Top 1 @TablaR = TablaR, @ColF = ColF, @ColR = ColR, @vchAlias = vchAlias From #tmpForeign Where tiProceso = 0
  1208.  
  1209.     -- Armo el From
  1210.     Select @vchFrom = @vchFrom + @TablaR + ' ' + @vchAlias  
  1211.  
  1212.     If @iHayMas = 1
  1213.         Set @vchFrom = @vchFrom + ', '
  1214.  
  1215.     If @iCont = 3 And @iHayMas = 1
  1216.         Select @iCont = 0, @vchFrom = @vchFrom + char(13) + char(10)
  1217.  
  1218.     -- Armo el Where:   A.Campo = B.Campo
  1219.     Select @vchWhere = @vchWhere + @vchAliasTabla + '.' + @ColF + ' = ' + @vchAlias + '.' + @ColR
  1220.  
  1221.     If @iHayMas = 1
  1222.         Set @vchWhere = @vchWhere + char(13) + char(10) + 'And '
  1223.  
  1224.     Update tmp Set tiProceso = 1 From #tmpForeign tmp Where TablaR = @TablaR And ColF = @ColF And ColR = @ColR And tiProceso = 0
  1225. End
  1226.  
  1227. If exists ( Select * From #tmpForeign Where tiProceso = 1 )
  1228.     Select 'Select * ' + char(13) + @vchFrom + ' ' + char(13) + @vchWhere
  1229. Else
  1230.     Select ''
  1231. Set nocount Off
  1232. GO
  1233.  
  1234.  
  1235. -- Procedimiento para generar el insert de los Errores del sistema enlace
  1236. If exists ( Select * From sysobjects Where name = 'sp_ppinInsertaObjetoError' )
  1237.     Drop procedure sp_ppinInsertaObjetoError
  1238. GO
  1239.  
  1240. Create Procedure sp_ppinInsertaObjetoError
  1241. (
  1242.     @vchNombreObjeto varchar(100) = '',
  1243.     @vchComentarioObjeto varchar(1024) = '',
  1244.     @iIdMensajeError int = 0,
  1245.     @vchMensajeError varchar(255) = '',
  1246.     @iIdTipoMensaje int = 5361,
  1247.     @tiEjecutaScript tinyint = 0
  1248. )
  1249. AS
  1250. /*
  1251. ** Nombre:              sp_ppinInsertaObjetoError
  1252. ** Propósito:              Insertar y devolver script de inserción de un error determinado a la tabla CatMensaje_ProcAlmacenado
  1253. ** Campos:              @vchNombreObjeto: Nombre del objeto al que se le insertará el error
  1254. **                      @vchComentarioObjeto: Comentario que tendrá el objeto en caso de no existir en CatGralObjeto
  1255. **                      @iIdMensajeError: ID del mensaje de error (el ID que devuelve el objeto cuando ocurre el error)
  1256. **                      @vchMensajeError: La descripción del mensaje de error (ej: 'la factura ya existe')
  1257. **                      @iIdTipoMensaje: Tipo de mensaje (catconstante, 5360, 4), por defecto, Crítico
  1258. **                      @tiEjecutaScript: Para indicar si además de generar el script, lo ejecuta (insert a catgralobjeto y/o CatMensaje_ProcAlmacenado)
  1259. ** Fecha creación:         2/Agosto/2007
  1260. ** Autor creación:         FDCG
  1261. ** Csd creación:           csd172
  1262. ** Fecha modificación:        
  1263. ** Autor modificación:        
  1264. ** Csd modificación:          
  1265. ** Compatibilidad:          1.75
  1266. ** Revisión:               0
  1267. */
  1268. Declare @iError int, @iIdObjeto int, @siTipoObjeto int, @iIdTipoObjeto_CC int
  1269. Declare @vchScript varchar(4000)
  1270. Set @iError = 0
  1271.  
  1272. Set nocount on
  1273.  
  1274. If len(ltrim(rtrim(@vchNombreObjeto))) = 0 Or @iIdMensajeError = 0 Or @vchMensajeError = ''
  1275. Begin
  1276.     Print 'Favor de proporcionar los siguientes parámetros: ' + char(13) + char(10) + char(13) + char(10)
  1277.     Print '@vchNombreObjeto: Nombre del objeto al que se le insertará el error'
  1278.     Print '@vchComentarioObjeto: Comentario que tendrá el objeto en caso de no existir en CatGralObjeto'
  1279.     Print '@iIdMensajeError: ID del mensaje de error (el ID que devuelve el objeto cuando ocurre el error)'
  1280.     Print '@iIdTipoMensaje: Tipo de mensaje (catconstante, 5360, 4), por defecto, Crítico'
  1281.     Print '@tiEjecutaScript: Para indicar si además de generar el script, lo ejecuta (insert a catgralobjeto y/o CatMensaje_ProcAlmacenado)'
  1282.     Set @iError = -1
  1283.     Goto _Fin
  1284. End
  1285.  
  1286. -- Si existe el mensaje, envío error
  1287. If exists ( Select * From bd_sicyproh..CatMensaje_ProcAlmacenado Where iIdMensaje = @iIdMensajeError )
  1288. Begin
  1289.     Print 'WARNING: El mensaje con ID ' + convert(varchar, @iIdMensajeError) + ' ya existe en la tabla bd_sicyproh..CatMensaje_ProcAlmacenado' + char(13) + char(10) + char(13) + char(10)
  1290.     Set @tiEjecutaScript = 0
  1291. End
  1292.  
  1293. -- Si no existe el objeto en el diccionario de datos, envío error
  1294. If not exists ( Select * From bd_sicyproh..trangraldiccionariodatos Where vchNombre = @vchNombreObjeto )
  1295. Begin
  1296.     Print 'ERROR: El objeto ' + @vchNombreObjeto + ' no existe en el diccionario de datos'
  1297.     Set @iError = -1
  1298.     Goto _Fin
  1299. End
  1300.  
  1301. -- Si no existe el objeto en CatGralObjeto, lo inserto
  1302. Select @iIdObjeto = iIdObjeto, @siTipoObjeto = siTipoObjeto, @iIdTipoObjeto_CC = DD.iReferencia
  1303. From bd_sicyproh..trangraldiccionariodatos GD, bd_sicyproh..CatConstanteDiccionarioDatos DD
  1304. Where GD.vchNombre = @vchNombreObjeto
  1305. And GD.siTipoObjeto = DD.siconsecutivo
  1306.  
  1307. If @iIdObjeto Is null
  1308. Begin
  1309.     Print 'ERROR: al obtener el ID del objeto'
  1310.     Set @iError = -1
  1311.     Goto _Fin
  1312. End
  1313.  
  1314. if not exists ( Select * From bd_sicyproh..catgralobjeto where iIdGralObjeto = @iIdObjeto )
  1315. Begin
  1316.     -- Armo la cadena del Insert a catgralobjeto y lo imprimo
  1317.     Set @vchScript = 'If not exists ( Select * From CatGralObjeto Where iIdGralObjeto = ' + convert(varchar, @iIdObjeto) + ' )' + char(13) + char(10)
  1318.     Set @vchScript = @vchScript + char(9) + 'Insert Into CatGralObjeto ( iIdGralObjeto, vchNombre, iIdTipoObjeto, tiActivo, vchComentario, tiBitacora )' + char(13) + char(10)
  1319.     Set @vchScript = @vchScript + char(9) + 'Values (' + convert(varchar, @iIdObjeto) + ', ''' + @vchNombreObjeto + ''', ' + convert(varchar, @iIdTipoObjeto_CC) + ', 1, ''' + @vchComentarioObjeto + ''', 0)' + char(13) + char(10)
  1320.     Set @vchScript = @vchScript + 'GO' + char(13) + char(10) + char(13) + char(10)
  1321.  
  1322.     Print @vchScript
  1323.     Set @vchScript = ''
  1324.  
  1325.     If @tiEjecutaScript <> 0
  1326.     Begin
  1327.         Insert Into bd_sicyproh..CatGralObjeto ( iIdGralObjeto, vchNombre, iIdTipoObjeto, tiActivo, vchComentario, tiBitacora )
  1328.         Values (@iIdObjeto, @vchNombreObjeto, @iIdTipoObjeto_CC, 1, @vchComentarioObjeto, 0)
  1329.     End
  1330.  
  1331.    
  1332. End
  1333.  
  1334.  
  1335. -- Insertar y devolver script de inserción a CatMensaje_ProcAlmacenado
  1336. Set @vchScript = 'If not exists ( Select * From CatMensaje_ProcAlmacenado Where iIdMensaje = ' + convert(varchar, @iIdMensajeError) + ' )' + char(13) + char(10)
  1337. Set @vchScript = @vchScript + char(9) + 'Insert Into CatMensaje_ProcAlmacenado (iIdMensaje, vchDescripcion, iIdGralObjeto, tiActivo, iIdTipoMensage)' + char(13) + char(10)
  1338. Set @vchScript = @vchScript + char(9) + 'Values (' + convert(varchar, @iIdMensajeError) + ', ''' + @vchMensajeError + ''', ' + convert(varchar, @iIdObjeto) + ', 1, ' + convert(varchar, @iIdTipoMensaje) + ')' + char(13) + char(10)
  1339. Set @vchScript = @vchScript + 'GO' + char(13) + char(10) + char(13) + char(10)
  1340.  
  1341. Print @vchScript
  1342. Set @vchScript = ''
  1343.  
  1344. If @tiEjecutaScript <> 0
  1345. Begin
  1346.     Insert Into bd_sicyproh..CatMensaje_ProcAlmacenado (iIdMensaje, vchDescripcion, iIdGralObjeto, tiActivo, iIdTipoMensage)
  1347.     Values (@iIdMensajeError, @vchMensajeError, @iIdObjeto, 1, @iIdTipoMensaje )
  1348. End
  1349.  
  1350.  
  1351. _Fin:
  1352. Set nocount off
  1353. Return @iError
  1354. GO
  1355.  
  1356. If exists ( Select * From sysobjects Where name = 'sp_ppinDependenciaSP' )
  1357.     Drop procedure sp_ppinDependenciaSP
  1358. GO
  1359. Create procedure sp_ppinDependenciaSP
  1360. (
  1361.     @vchSP varchar(255),
  1362.     @niveles int
  1363. )
  1364. AS
  1365. /*
  1366. ** Nombre:              sp_ppinDependenciaSP
  1367. ** Propósito:              Devuelve las dependencias por exec dentro de un SP según la cantidad de niveles máximos indicados.
  1368. **                      O sea, si el procedimiento p01 llama al procedimiento p02 y éste a su vez al p03,
  1369. **                      se devolverán los tres procedimientos llamando a este SP con los parámetros: sp_ppinDependenciaSP 'p01', 3
  1370. ** Campos:              @vchSP: Nombre del procedimiento (nivel 0)
  1371. **                      @niveles: cantidad máxima de niveles a escanear
  1372. ** Fecha creación:         12/Enero/2009
  1373. ** Autor creación:         FDCG
  1374. ** Revisión:               0
  1375. */
  1376. Set nocount on
  1377.  
  1378. Declare @iNivel int, @id int
  1379. Set @iNivel = 1
  1380.  
  1381. If object_id(@vchSP) Is null
  1382. Begin
  1383.     print 'El objeto [' + @vchSP + '] no existe en [' + db_name() + ']'
  1384.     Return 1
  1385. End
  1386.  
  1387. Create Table #tmpDepends
  1388. (
  1389.     id int,
  1390.     name sysname,
  1391.     nivel int
  1392. )
  1393.  
  1394. Insert Into #tmpDepends (id, name, nivel)
  1395. Select Object_id(@vchSP), Object_name(Object_id(@vchSP)), 0
  1396.  
  1397. While (@iNivel <= @niveles)
  1398. Begin
  1399.     Insert Into #tmpDepends (id, name, nivel)
  1400.     Select distinct d.depid, o.name, @iNivel
  1401.     From sysdepends d, sysobjects o, #tmpDepends t
  1402.     Where d.id = t.id
  1403.     and d.depid = o.id
  1404.     and o.xtype = 'P'
  1405.     and not exists ( Select * From #tmpDepends t2 where t2.id = d.depid )
  1406.  
  1407.     Set @iNivel = @iNivel + 1
  1408. End
  1409.  
  1410. Print 'Dependencias por exec del objeto ' + @vchSP + ':'
  1411. Select Convert(varchar(100), Space(nivel * 2) + name) as NombreNivel, nivel, id, name
  1412. From #tmpDepends
  1413.  
  1414. Set nocount off
  1415. Return 0
  1416. GO
  1417.  
  1418. If exists ( Select * From sysobjects Where name = 'sp_ppinGeneraScriptObjeto' )
  1419.     Drop procedure sp_ppinGeneraScriptObjeto
  1420. GO
  1421. CREATE procedure dbo.sp_ppinGeneraScriptObjeto
  1422. (
  1423. @iAccion int = 0,
  1424. @vchValor1 varchar(512) = '',
  1425. @vchValor2 varchar(512) = '',
  1426. @vchValor3 varchar(512) = '',
  1427. @vchValor4 varchar(512) = '',
  1428. @vchValor5 varchar(512) = '',
  1429. @vchValor6 varchar(512) = NULL
  1430. )
  1431. AS
  1432. /* Federico Colombo */
  1433. /*
  1434. ** Nombre:      sp_ppinGeneraScriptObjeto
  1435. ** Propósito:  Procedimiento almacenado para facilir el manejo o manipulacion de la base de datos
  1436. ** Campos:          @iAccion -->0       ejecuta un sp_helptext de este procedimiento almacenado
  1437. **                         
  1438. **                  @iAccion -->1       Arma el query para eliminar o crear un objeto de la base de datos. El crear o eliminar depende del tipo de objeto
  1439. **                                  @vchValor1      Nombre del objeto (Requerido)
  1440. **
  1441. **                  @iAccion -->2       Retorna los objecto que cumplen los criterios proporcionado (Nombre o parte del nombre)
  1442. **                                  @vchValor1      Nombre del objeto (Requerido)
  1443. **                                  @vchValor2      Tipo de objeto (opcional)
  1444. **                  @iAccion -->3       Retorna los objetos que contienen en el cuerpo del mismo un texto (procedimientos, vistas y triggers)
  1445. **                                  @vchValor1      Texto a busca (Requerido)
  1446. **                                  @vchValor2      Tipo de objeto (opcional)
  1447. **                  @iAccion -->4       Retorna las columnas de una tabla o vista o parámetros de un SP separados por coma
  1448. **                                  @vchValor1      Nombre de la Tabla, vista o SP
  1449. **                                  @vchValor2      Cantidad de columnas por cada fila devuelta
  1450. **                                  @vchValor3      Alias de la tabla
  1451. **                                  @vchValor4      Enviar el numéro uno si se quiere que lugar de separar los campos
  1452. **                                                              por espacios se desea separarlos por tabuladores.
  1453. **                  @iAccion -->5       Retorna el script CREATE TABLE de la tabla existente proporcionada
  1454. **                                  @vchValor1      Nombre de la Tabla
  1455. **                  @iAccion -->6       Retorna los comentarios que deben llevar los objetos de la base datos
  1456. **
  1457. **                  @iAccion -->7   Generates the constant insert/update script
  1458. **                                      vchValor1: The id used for the first constant id, and also used for the group id
  1459. **                                      vchValor2: The name of the new group
  1460. **                                      vchValor3: Comma separated values of names, with the names and friendly names that the constants will have.
  1461. **                                                  Any item could be optionally separated into name and friendly name by a "|"
  1462. **                                                  i.e.: "Open|Connection is open,Closed|Connection is closed"
  1463. **
  1464. **                  @iAccion -->8       Genera automáticamente un script con los alter table (drop o add) de los constraints
  1465. **                                  que hacen referencia (foránea) a la tabla especificada
  1466. **                                  @vchValor1      Nombre de la Tabla
  1467. **                                  @vchValor2      0: Genera los Add Constraint (por defecto)
  1468. **                                              1: Genera los Drop Constraint
  1469. **                  @iAccion -->9       Genera el script que inserta los datos de una tabla
  1470. **                                  @vchValor1      Nombre de la Tabla
  1471. **                                  @vchValor2      Cláusula where a usar (opcional)
  1472. **                                  @vchValor3      Tipo de resultado: 0: Genera el If Exists->Delete->Insert (dafault)
  1473. **                                                                   1: Genera el If Not Exists->Insert
  1474. **                  @iAccion -->10      Muestra la consulta al diccionario de datos para un objeto dado
  1475. **                                  @vchValor1      Nombre del objeto.
  1476. **                  @iAccion -->11      Retorna las consultas a las listas y constantes mas usuales
  1477. **                                  @vchValor1 Nombre de la tabla, si se envia un vacio se retorna todas las tablas ( catconstante, sysvalorlista, catvaloreslista, sysparametro, configuracion)
  1478. **                                  @vchValor2 Valor para el filtro, si se envia un vacio no se coloca ningun filtro
  1479. **                                  @vchValor3 Campo por que se quiere filtrar(nombre) o enviar un uno para filtrar por el consecutivo y un 2
  1480. **                                  para filtrar por el agrupador, si se envia un vacio se filtra por el consecutivo (llave de la tabla).
  1481. **                  @iAccion -->12      Retorna los objectos que hacen un insert a x tabla de la base de datos
  1482. **                                  @vchValor1 Nombre de la tabla, debe especificarse una sola tabla
  1483. **                                  @vchValor2 Tipo de objeto (<p>-->Procedimientos almacenados, <TR>--Trigrer, <vacío>-->Sin filtrar el tipo de objeto.
  1484. **                                  @vchValor4 varchar(512) = '',
  1485. **                                  @vchValor5 varchar(512) = '',
  1486. **                                  @vchValor6      Filtro
  1487. **                  @iAccion -->13      Dada una tabla y un alias para la misma, Retorna un SELECT con FROM y WHERE según sus llaves foráneas
  1488. **                                  @vchValor1 Nombre de la tabla
  1489. **                                  @vchValor2 Alias que tendrá la tabla en el select devuelto
  1490. **
  1491. **                  @iAccion -->14      Dado un comando del shell lo ejecuta y devuelve el output
  1492. **                                  @vchValor1: Comando. por ejemplo: 'dir *.exe'
  1493. **
  1494. **                  @iAccion -->15      Devuelve los inserts a CatGralObjeto y CatEspObjeto para una tabla que existe en el diccionario de datos
  1495. **                                  @vchValor1: Nombre de la tabla. por ejemplo: 'ACFMATE1'
  1496. **
  1497. **                  @iAccion -->16      Devuelve las dependencias de un SP (execs anidados a otros SPs)
  1498. **                                  @vchValor1: Nombre del procedimiento almacenado
  1499. **                                  @vchValor2: Cantidad máxima de niveles de anidamiento
  1500. **
  1501. ** Dependencias:    
  1502. **
  1503. ** Fecha creación:     12/Noviembre/2005
  1504. ** Autor creación:     CJFU
  1505. ** Fecha modificación:     24/11/05, 03-03-07, 05-07-06, 01-08-07, 30-04-08, 12-01-09, 26/Febrero/2010
  1506. ** Autor modificacion:  FDCG, FDCG, FDCG, FDCG, FDCG, FDCG, CJFU
  1507. ** Compatibilidad:  1.75
  1508. ** Revision:        9
  1509. */
  1510. Declare @vchQuery varchar(4000)
  1511. Declare @tipoObj varchar(100)
  1512.  
  1513. If @iAccion = 0 --Ejecutar sp_helptext de este procedimiento almacenado
  1514.     Begin
  1515.         Select c.text
  1516.         From master..sysobjects o, master..syscomments c
  1517.         Where o.id = c.id
  1518.         And o.name = 'sp_ppinGeneraScriptObjeto'
  1519.     End
  1520.  
  1521. If @iAccion = 1 --Drop
  1522.     Begin
  1523.         If rtrim(ltrim(@vchValor1)) = ''
  1524.         Begin
  1525.             Print 'Esta accion es para la validación de la creaccion/eliminacion de un objeto '
  1526.             Print '(creacion para tablas, reportes o campos de tablas y eliminacion para el resto de objetos'
  1527.             Print 'Favor de proporcionar el nombre del objeto'
  1528.             Print '@vchValor1       -->Nombre del objeto'
  1529.             Print '@vchValor2       -->Nombre del campo (siempre y cuando sea una tabla)'
  1530.         End
  1531.         Else
  1532.         If Substring(@vchValor1, 1, 1) = '#'    -- Si es una temporal
  1533.             Begin
  1534.                 Select Top 1 'If exists ( Select * From tempdb..sysobjects Where name like ''' + @vchValor1 + '[_]%'' ) ' + char(13) + Char(10) + char(9) + 'Drop ' + @vchValor1 + char(13) + Char(10) + 'GO' + char(13) + Char(10)
  1535.                 From tempdb..sysobjects o
  1536.                 Where o.name like @vchValor1 + '[_]%'
  1537.             End
  1538.         Else If substring(@vchValor1, len(@vchValor1) -3, 4) = '.rpt'--Es un reporte
  1539.         Begin
  1540.             Exec SP_PpInGenera_ScriptRpt
  1541.             @vchNombreReporte = @vchValor1
  1542.         End
  1543.         Else
  1544.             Begin
  1545.                
  1546.                 Set @vchValor2 = ltrim(rtrim(@vchValor2))
  1547.                 --Revisar si es una tabla, si es así para cambiar que en lugar del exists sea un not exists
  1548.                 If exists ( Select * From sysobjects o
  1549.                     Where o.name = @vchValor1 And o.xtype = 'U' ) --Tabla
  1550.                 Begin
  1551.                     --Si no se está enviando el segundo parametro, quiere decir que unicamente se quiere el if not exists
  1552.                     If @vchValor2 = '' or @vchValor2 is null
  1553.                     Begin
  1554.                         --Select 'If not exists ( Select * From sysobjects Where name = ''' + name + ''' ) '
  1555.                         Select 'If OBJECT_ID(''' + name + ''', ''U'') Is Null'
  1556.                         From sysobjects o
  1557.                         Where o.name = @vchValor1                      
  1558.                     End
  1559.                     Else
  1560.                     Begin
  1561.                         Select 'If not exists ( Select * From sysobjects o, syscolumns c Where o.id = c.id' + char(13)  + Char(10)+ char(9) +
  1562.                             'And o.name = ''' + o.name + ''' And c.name = ''' + @vchValor2 + ''' ) '
  1563.                         From sysobjects o
  1564.                         Where o.name = @vchValor1
  1565.                     End
  1566.                 End
  1567.                 Else
  1568.                 Begin
  1569.                     Select @tipoObj = Case When xtype = 'P' Then 'Procedure' When xtype = 'V' Then 'View' When xtype = 'TR' Then 'Trigger' Else '' End
  1570.                     From sysobjects where name = @vchValor1
  1571.                     Select 'If exists ( Select * From sysobjects Where name = ''' + name + ''' ) ' + char(13) + Char(10) + char(9) + 'Drop ' + @tipoObj + ' ' + name + char(13) + Char(10) + 'GO' + char(13) + Char(10)
  1572.                     From sysobjects o
  1573.                     Where o.name = @vchValor1
  1574.                 End
  1575.             End
  1576.     End
  1577. If @iAccion = 2 --Nombres like...
  1578.         If rtrim(ltrim(@vchValor1)) = ''
  1579.             Print 'Favor de proporcionar el filtro'
  1580.         Else
  1581.         Begin
  1582.             Set @vchQuery  = 'Select Distinct o.name '
  1583.             Set @vchQuery  = @vchQuery + 'From sysobjects o '
  1584.             Set @vchQuery  = @vchQuery + 'Where o.name like ' + char(39) + '%' + @vchValor1 + '%' + char(39) + ' '
  1585.             If @vchValor2 <> ''
  1586.                 Set
  1587.  @vchQuery  = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1588.             Exec ( @vchQuery  )
  1589.  
  1590.             Select @vchQuery as vchQuery
  1591.         End
  1592. If @iAccion = 3 --Comentarios like
  1593.         If rtrim(ltrim(@vchValor1)) = ''
  1594.             Print 'Favor de proporcionar el filtro'
  1595.         Else
  1596.         Begin
  1597.            
  1598.             Set @vchQuery  = 'Select Distinct o.name '
  1599.             Set @vchQuery  = @vchQuery + 'From sysobjects o, syscomments c '
  1600.             Set @vchQuery  = @vchQuery + 'Where o.id = c.id '
  1601.             Set @vchQuery  = @vchQuery + 'And c.text like ' + char(39) + '%' + @vchValor1 + '%' + char(39) + ' '
  1602.             If @vchValor2 <> ''
  1603.                 Set @vchQuery  = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1604.             Set @vchQuery  = @vchQuery + ' And o.name <> ''' + @vchValor1 + ''' '
  1605.             Exec ( @vchQuery  )
  1606.  
  1607.             Select @vchQuery as vchQuery
  1608.         End
  1609.  
  1610. If @iAccion = 4 -- Campos de una tabla o vista ó parámetros de un SP separados por coma
  1611. Begin
  1612.         If rtrim(ltrim(@vchValor1)) = ''
  1613.             Print 'Favor de proporcionar el nombre del objeto'
  1614.         Else
  1615.         Begin
  1616.             Declare @ColName varchar(70), @cont int
  1617.  
  1618.             Create Table #tmpColumnas (
  1619.                 ya smallint default(0),
  1620.                 colName varchar(200),
  1621.             )
  1622.             Set nocount on
  1623.            
  1624.             If @vchValor3 is null
  1625.             Begin
  1626.                     Set @vchValor3 = ''
  1627.             End
  1628.             Else
  1629.             Begin--eliminar los espacios
  1630.                 Set @vchValor3 = rtrim(ltrim(@vchValor3))
  1631.             End
  1632.    
  1633.             If @vchValor3 <> ''
  1634.             Begin
  1635.                 Set @vchValor3 = @vchValor3 + '.'
  1636.             End
  1637.  
  1638.             If exists (Select * from sysobjects where name = @vchValor1 and type IN ('U', 'S', 'V', 'P'))
  1639.             BEGIN
  1640.                 Insert #tmpColumnas
  1641.                 Select 0, @vchValor3 + '[' + c.name + ']'
  1642.                 From sysobjects o, syscolumns c
  1643.                 Where o.id = c.id
  1644.                 AND o.name = @vchValor1
  1645.                 Order by c.colid
  1646.             END
  1647.             ELSE
  1648.             BEGIN
  1649.                 If exists ( Select * from tempdb..sysobjects where name like @vchValor1 + '[_]%' )
  1650.                 Begin
  1651.                     -- Es una tabla temporal
  1652.                     Insert #tmpColumnas
  1653.                     Select 0, @vchValor3 + '[' + c.name + ']'
  1654.                     From tempdb..sysobjects o, tempdb..syscolumns c
  1655.                     Where o.id = c.id
  1656.                     AND o.name = (Select Top 1 name From tempdb..sysobjects Where name like @vchValor1 + '[_]%')
  1657.                     Order by c.colid                   
  1658.                 End
  1659.                 Else
  1660.                 Begin
  1661.                     -- No existe o no es un objeto válido
  1662.                     If object_id(@vchValor1) Is Null
  1663.                         Print 'El objeto [' + @vchValor1 + '] no existe en [' + db_name() + ']'
  1664.                     else
  1665.                         Print 'El objeto [' + @vchValor1 + '] no es un objeto válido'
  1666.                     Return -1
  1667.                 End
  1668.             END
  1669.            
  1670.             Update tmp
  1671.             Set colName = colName
  1672.             From #tmpColumnas tmp
  1673.            
  1674.             Set @vchQuery = ''
  1675.             If (@vchValor2 = '')
  1676.                 Set @vchValor2 = '0'
  1677.             Set @cont = 0
  1678.             while exists (Select * From #tmpColumnas Where ya=0)
  1679.                 Begin
  1680.                     Select TOP 1 @ColName = colName From #tmpColumnas Where ya=0
  1681.                     Update #tmpColumnas Set ya = 1 Where colName = @colName
  1682.                     Set @vchQuery = @vchQuery + @ColName
  1683.  
  1684.                     If @vchValor4 = 1
  1685.                     Begin
  1686.                         Set @vchQuery = @vchQuery + char(9)
  1687.                     End        
  1688.                     Else If exists (Select * From #tmpColumnas Where ya=0)
  1689.                     Begin
  1690.                         Set @vchQuery = @vchQuery + ', '
  1691.                     End
  1692.  
  1693.                     Set @cont = @cont + 1
  1694.                     If @cont = Convert(int, @vchValor2)
  1695.                         BEGIN
  1696.                             Set @vchQuery = @vchQuery + char(13) + Char(10)
  1697.                             Set @cont = 0
  1698.                         END
  1699.                 End
  1700.             Set nocount off
  1701.             Select @vchQuery
  1702.  
  1703.         End
  1704.     End
  1705.  
  1706. If @iAccion = 5     -- Create Table con los campos, tipo, longitud y nullable
  1707.     Begin
  1708.         If rtrim(ltrim(@vchValor1)) = ''
  1709.             Print 'Favor de proporcionar el nombre del objeto'
  1710.         Else
  1711.         Begin
  1712.             Exec sp_ppinScriptTabla @vchValor1
  1713.         End
  1714.     End
  1715.  
  1716. If @iAccion = 6     --Retorna los comentarios que deberán llevar los objetos de la base de datos (triggers, vistas y procedimientos almacenados)
  1717.     Begin
  1718.         Declare @type varchar(100)
  1719.         Declare @v varchar(max)
  1720.         Declare @nextCode varchar(12)
  1721.         Declare @description varchar(max)
  1722.         If len(rtrim(ltrim(@vchValor1))) = 0
  1723.             set @type = 'text'
  1724.         else
  1725.             set @type = @vchValor1
  1726.         If len(rtrim(ltrim(@vchValor2))) = 0
  1727.             Set @description = '?????'
  1728.         else
  1729.             Set @description = @vchValor2
  1730.         Select @nextCode = cast(Max(Code)+1 as varchar) From d_FFRts..rtslanguage Where [Type] = @type
  1731.         If @nextCode is null
  1732.         begin
  1733.             Print 'Type "' + @type + '" not found.'
  1734.             Print ''
  1735.         end
  1736.         Set @v = 'If Exists (Select * From rtslanguage Where code = ''' + @nextCode + ''' and [Language] = ''English [US]'')' + char(13) + Char(10)
  1737.         Set @v = @v + ' Update rtslanguage' + char(13) + Char(10)
  1738.         Set @v = @v + ' Set [Language] = ''English [US]'', ' + char(13) + Char(10)
  1739.         Set @v = @v + ' [Type] = ''' + @type + ''', ' + char(13) + Char(10)
  1740.         Set @v = @v + ' [Code] = ''' + @nextCode + ''', ' + char(13) + Char(10)
  1741.         Set @v = @v + ' [Description] = ''' + @description + ''', ' + char(13) + Char(10)
  1742.         Set @v = @v + ' [StatusID] = 1' + char(13) + Char(10)
  1743.         Set @v = @v + ' Where code = ''' + @nextCode + ''' and [Language] = ''English [US]''' + char(13) + Char(10)
  1744.         Set @v = @v + 'Else' + char(13) + Char(10)
  1745.         Set @v = @v + ' Insert Into rtslanguage([Language], [Type], [Code], [Description], [StatusID])' + char(13) + Char(10)
  1746.         Set @v = @v + ' Values (''English [US]'', ''' + @type + ''', ''' + @nextCode + ''', ''' + @description + ''', 1)' + char(13) + Char(10)
  1747.         Set @v = @v + 'GO'
  1748.         Print @v
  1749.     End
  1750. If @iAccion = 7 -- Generate the constant insert/update script
  1751.     Begin
  1752.         Exec ('sp_GenerateConstantScript ' + @vchValor1 + ', ''' + @vchValor2 + ''', ''' +  @vchValor3 + '''')
  1753.     End
  1754. If @iAccion = 8 --SP_AddDrop_ForeignKeys
  1755. Begin
  1756.     Exec ('SP_ppinAddDrop_ForeignKeys ''' + @vchValor1 + ''',''' + @vchValor2 + '''')
  1757. End
  1758. If @iAccion = 9 --SP_Genera_Insert
  1759.     Exec ('SP_ppinGenera_Insert ''' + @vchValor1 + ''',''' + @vchValor2 + ''', ' + @vchValor3)
  1760. If @iAccion = 10 --Consulta al diccionario de datos
  1761. Begin
  1762.     Set Nocount On
  1763.     Select CC2.vchdescripcion AS Base, G.vchNombreObjeto, CC1.vchdescripcion AS TipoObjeto,
  1764.     CC3.vchdescripcion AS Modulo,   vchDescripcionObjeto, E.vchNombreCampo, E.vchDescripcionCampo, G.siTipoObjeto,
  1765.     G.iIdObjeto
  1766.     Into #tmpAccion10
  1767.     From bd_sicyproh..vpinGralDiccionarioDatos G, bd_sicyproh..vpinEspDiccionarioDatos E,
  1768.     bd_sicyproh..CatConstanteDiccionarioDatos CC1, bd_sicyproh..CatConstanteDiccionarioDatos CC2,
  1769.     bd_sicyproh..CatConstanteDiccionarioDatos CC3
  1770.     Where G.iIdObjeto=E.iIdObjeto
  1771.     And CC1.siconsecutivo = G.siTipoObjeto
  1772.     And CC2.siconsecutivo = G.siBaseDatos
  1773.     And CC3.siconsecutivo = G.siIdModulo
  1774.     And vchNombreObjeto = @vchValor1
  1775.     And CC2.vchdescripcion = db_name()
  1776.    
  1777.  
  1778.     If Not Exists ( Select * From #tmpAccion10 )
  1779.     Begin
  1780.         Print 'El objeto [' + @vchValor1 + '] no existe en el diccionario de datos para [' + db_name() + ']'
  1781.         Return -1
  1782.     End
  1783.    
  1784.     Declare @tmpBase varchar(512), @tmpObjeto varchar(512), @tmpTipoObjeto varchar(512), @tmpDescripcionObjeto varchar(1000)
  1785.     Declare @tmpTipo smallint, @tmpModulo varchar(512), @iIdObjeto int
  1786.     Declare @tmpCampo varchar(512), @tmpDesc varchar(1000)
  1787.     Select Top 1 @tmpBase = Base, @tmpObjeto = vchNombreObjeto, @tmpTipoObjeto = TipoObjeto,
  1788.     @tmpDescripcionObjeto = vchDescripcionObjeto, @tmpTipo = siTipoObjeto, @tmpModulo = Modulo, @iIdObjeto = iIdObjeto
  1789.     From #tmpAccion10
  1790.  
  1791.     Print '---------------- CONSULTA AL DICCIONARIO DE DATOS ----------------'
  1792.     Print 'Objeto: [' + @tmpTipoObjeto + '] ' + @tmpBase + '..' + @tmpObjeto + ' (' + @tmpDescripcionObjeto + ')' + char(13) + Char(10) + 'ID Objeto: ' + convert(varchar, @iIdObjeto) + char(13) + Char(10)
  1793.     Print 'Módulo: ' + @tmpModulo + char(13) + Char(10) + char(13) + Char(10)
  1794.     if @tmpTipo = 1     -- Store Procedure
  1795.         Select '@' + vchNombreCampo AS Parametro, Replace(vchDescripcionCampo,char(13)+char(10),' ') AS Descripcion From #tmpAccion10
  1796.     Else
  1797.         Select vchNombreCampo AS Campo, Replace(vchDescripcionCampo,char(13)+char(10),' ') AS Descripcion From #tmpAccion10
  1798.     Set Nocount Off
  1799. End
  1800.  
  1801. If @iAccion = 11 --Retornar las consultas de tablas de listas más usuales
  1802. Begin
  1803.     If @vchValor1 = ''
  1804.     Begin
  1805.         Select @vchQuery = 'Select * From catconstante '
  1806.             + case @vchValor2 when '' then ''
  1807.                 else 'Where ' +
  1808.                     case @vchValor3 when '' then 'siconsecutivo = ' + @vchValor2
  1809.                                                     when '1' then 'siconsecutivo = ' + @vchValor2
  1810.                                                     when '2' then 'siagrupador = ' + @vchValor2
  1811.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1812.             end--Fin del case
  1813.             + char(13) + Char(10)  --Un enter
  1814.         Select @vchQuery = @vchQuery + 'Select * From sysvalorlista '
  1815.             + case @vchValor2 when '' then ''
  1816.                 else 'Where ' +
  1817.                     case @vchValor3 when '' then 'siConsecutivo = ' + @vchValor2
  1818.                                                     when '1' then 'siConsecutivo = ' + @vchValor2
  1819.                                                     when '2' then 'siAgrupador = ' + @vchValor2
  1820.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1821.             end--Fin del case
  1822.             + char(13) + Char(10) --Un enter
  1823.         Select @vchQuery = @vchQuery + 'Select * From catvaloreslista '
  1824.             + case @vchValor2 when '' then ''
  1825.                 else 'Where ' +
  1826.                     case @vchValor3 when '' then 'iconsecutivo = ' + @vchValor2
  1827.                                                     when '1' then 'iconsecutivo = ' + @vchValor2
  1828.                                                     when '2' then 'sicodpal = ' + @vchValor2
  1829.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1830.             end--Fin del case
  1831.             + char(13) + Char(10)
  1832.         Select @vchQuery = @vchQuery + 'Select * From sysparametro '
  1833.             + case @vchValor2 when '' then ''
  1834.                 else 'Where ' +
  1835.                     case @vchValor3 when '' then 'iCodParametro = ' + @vchValor2
  1836.                
  1837.                                     when '1' then 'iCodParametro = ' + @vchValor2
  1838.                                                     when '2' then 'siAgrupador = ' + @vchValor2
  1839.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1840.             end--Fin del case
  1841.             + char(13) + Char(10)
  1842.         Select @vchQuery = @vchQuery + 'Select * From configuracion '
  1843.             + case @vchValor2 when '' then ''
  1844.                 else 'Where ' +
  1845.                     case @vchValor3 when '' then 'iCodConfiguracion = ' + @vchValor2
  1846.                                                     when '1' then 'iCodConfiguracion = ' + @vchValor2                                                  
  1847.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1848.             end--Fin del case
  1849.             + char(13) + Char(10)
  1850.     End
  1851.     Else
  1852.     Begin
  1853.         Select @vchQuery + 'Select * From ' + @vchValor1 + ' '
  1854.             + case @vchValor2 when '' then ''
  1855.                 else 'Where ' +
  1856.                     case @vchValor3 when '' then 'iConsecutivo = ' + @vchValor2
  1857.                                                     when '1' then 'iConsecutivo = ' + @vchValor2
  1858.                                                     when '2' then 'iAgrupador = ' + @vchValor2                                                 
  1859.                                                     else @vchValor3 + ' = ' + @vchValor2 end
  1860.             end--Fin del case
  1861.     End
  1862.     Select @vchQuery as vchQuery
  1863. End
  1864.  
  1865. If @iAccion = 12 --Retornar las consultas de tablas de listas más usuales
  1866. Begin
  1867.     Set @vchValor1 = ltrim(rtrim(@vchValor1))
  1868.     Set @vchValor2 = ltrim(rtrim(@vchValor2))
  1869.     If @vchValor1 <> '' And @vchValor1 is not null
  1870.     Begin
  1871.         --Insert con un espacio
  1872.         Set @vchQuery = 'Select Distinct o.name '
  1873.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1874.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1875.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%insert ' + @vchValor1 + '%' + char(39) + ' '
  1876.         If @vchValor2 <> '' And @vchValor2 is not null
  1877.         Begin
  1878.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1879.         End
  1880.         --Insert con dos espacios
  1881.         Set @vchQuery = @vchQuery + 'Union all '       
  1882.         Set @vchQuery = @vchQuery + 'Select Distinct o.name '
  1883.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1884.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1885.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%insert  ' + @vchValor1 + '%' + char(39) + ' '
  1886.         If @vchValor2 <> '' And @vchValor2 is not null
  1887.         Begin
  1888.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1889.         End
  1890.         --Insert con tabulador
  1891.         Set @vchQuery = @vchQuery + 'Union all '       
  1892.         Set @vchQuery = @vchQuery + 'Select Distinct o.name '
  1893.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1894.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1895.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%insert    ' + @vchValor1 + '%' + char(39) + ' '
  1896.         If @vchValor2 <> '' And @vchValor2 is not null
  1897.         Begin
  1898.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1899.         End
  1900.         --Into con un espacio
  1901.         Set @vchQuery = @vchQuery + 'Union all '       
  1902.         Set @vchQuery = @vchQuery + 'Select Distinct o.name '
  1903.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1904.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1905.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%into ' + @vchValor1 + '%' + char(39) + ' '
  1906.         If @vchValor2 <> '' And @vchValor2 is not null
  1907.         Begin
  1908.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1909.         End
  1910.         --Into con dos espacios
  1911.         Set @vchQuery = @vchQuery + 'Union all '       
  1912.         Set @vchQuery = @vchQuery + 'Select Distinct o.name '
  1913.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1914.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1915.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%Into  ' + @vchValor1 + '%' + char(39) + ' '
  1916.         If @vchValor2 <> '' And @vchValor2 is not null
  1917.         Begin
  1918.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1919.         End
  1920.         --Into con tabulador
  1921.         Set @vchQuery = @vchQuery + 'Union all '       
  1922.         Set @vchQuery = @vchQuery + 'Select Distinct o.name '
  1923.         Set @vchQuery = @vchQuery + 'From sysobjects o, syscomments c '
  1924.         Set @vchQuery = @vchQuery + 'Where o.id = c.id '
  1925.         Set @vchQuery = @vchQuery + 'And c.text like ' + char(39) + '%Into  ' + @vchValor1 + '%' + char(39) + ' '
  1926.         If @vchValor2 <> '' And @vchValor2 is not null
  1927.         Begin
  1928.             Set @vchQuery = @vchQuery + 'And o.type = ' + char(39) + @vchValor2 + char(39) + ' '
  1929.  
  1930.         End
  1931.         Execute ( @vchQuery )
  1932.         Select @vchQuery as vchQuery
  1933.     End
  1934.     Else
  1935.     Begin
  1936.         Select 'Favor de proporcionar el nombre la de la tabla'
  1937.         Select '@iAccion -->12      Retorna los objectos que hacen un insert a x tabla de la base de datos'
  1938.         Select '@vchValor1 Nombre de la tabla, debe especificarse una sola tabla'
  1939.         Select '@vchValor2 Tipo de objeto (<p>-->Procedimientos almacenados, <TR>--Trigrer, <vacío>-->Sin filtrar el tipo de objeto.'
  1940.     End
  1941. End
  1942.  
  1943. If @iAccion = 13 -- Retornar SELECT de una tabla según sus llaves foráneas
  1944. Begin
  1945.     If @vchValor2 = '' Set @vchValor2 = 'A'
  1946.     Exec ('sp_ppinSelectFromWhereForaneo ''' + @vchValor1 + ''',''' + @vchValor2 + '''')
  1947. End
  1948.  
  1949. If @iAccion = 14 -- cmdShell
  1950. Begin
  1951.     Exec ('master..xp_cmdshell ''' + @vchValor1 + '''')
  1952. End
  1953.  
  1954. If @iAccion = 15 -- Inserts a CatGralObjeto y CatEspObjeto
  1955. Begin
  1956.     Exec ('sp_ppinTablaCatObjeto ''' + @vchValor1 + '''')
  1957. End
  1958.  
  1959. If @iAccion = 16 -- Dependencias por execs anidados
  1960. Begin
  1961.     If len(ltrim(rtrim(@vchValor2))) = 0
  1962.         Set @vchValor2 = '10'
  1963.     Exec ('sp_ppinDependenciaSP ''' + @vchValor1 + ''', ' + @vchValor2)
  1964. End
  1965. GO
  1966.  
  1967. If exists ( Select * From sysobjects Where name = 'sp_ppinSeparaParametro_ScrObj' )
  1968.     Drop procedure sp_ppinSeparaParametro_ScrObj
  1969. GO
  1970.  
  1971. CREATE  procedure sp_ppinSeparaParametro_ScrObj
  1972. @vchParametro varchar(1024)
  1973. AS
  1974. Declare @tiHayComa tinyint
  1975. Set @tiHayComa = 0
  1976.  
  1977. Declare @vchParametro1 varchar(50)
  1978. Declare @vchParametro2 varchar(50)
  1979. Declare @vchParametro3 varchar(50)
  1980. Declare @vchParametro4 varchar(50)
  1981. Declare @vchParametro5 varchar(50)
  1982. Declare @vchParametro6 varchar(50)
  1983. Declare @vchParametro7 varchar(50)
  1984. Declare @vchParametro8 varchar(50)
  1985. Declare @vchParametro9 varchar(50)
  1986. Declare @vchParametro10 varchar(50)
  1987.  
  1988. Declare @iParametroNum1 int
  1989. Declare @iParametroNum2 int
  1990.  
  1991. Set @vchParametro1 = ''
  1992. Set @vchParametro2  = ''
  1993. Set @vchParametro3  = ''
  1994. Set @vchParametro4  = ''
  1995. Set @vchParametro5  = ''
  1996. Set @vchParametro6  = ''
  1997. Set @vchParametro7  = ''
  1998. Set @vchParametro8  = ''
  1999. Set @vchParametro9  = ''
  2000. Set @vchParametro10  = ''
  2001.  
  2002. Set @iParametroNum1 = 0
  2003. Set @iParametroNum2  = 0
  2004.  
  2005. --eliminar los espacios al inicio y al final
  2006. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2007.  
  2008. --Obtener el primer parametro
  2009. Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2010. If @tiHayComa >= 1
  2011. Begin
  2012.     Select @vchParametro1 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2013.     --Eliminar de la cadena el parametro obtenido
  2014.     Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2015. End
  2016. Else --si no hay coma
  2017. Begin
  2018.     Select @vchParametro1 = @vchParametro
  2019.     --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2020.     Select @vchParametro = ''
  2021. End
  2022.  
  2023. --eliminar los espacios al inicio y al final
  2024. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2025.  
  2026. --Obtener el segundo parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2027. If @vchParametro <> ''
  2028. Begin
  2029.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2030.     If @tiHayComa >= 1
  2031.     Begin
  2032.         Select @vchParametro2 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2033.         --Eliminar de la cadena el parametro obtenido
  2034.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2035.     End
  2036.     Else --si no hay coma
  2037.     Begin
  2038.         Select @vchParametro2 = @vchParametro
  2039.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2040.         Select @vchParametro = ''
  2041.     End
  2042. End
  2043.  
  2044. --eliminar los espacios al inicio y al final
  2045. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2046.  
  2047. --Obtener el tercer parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2048. If @vchParametro <> ''
  2049. Begin
  2050.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2051.     If @tiHayComa >= 1
  2052.     Begin
  2053.         Select @vchParametro3 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2054.         --Eliminar de la cadena el parametro obtenido
  2055.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2056.     End
  2057.     Else --si no hay coma
  2058.     Begin
  2059.         Select @vchParametro3 = @vchParametro
  2060.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2061.         Select @vchParametro = ''
  2062.     End
  2063. End
  2064.  
  2065. --eliminar los espacios al inicio y al final
  2066. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2067.  
  2068. --Obtener el cuarto parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2069. If @vchParametro <> ''
  2070. Begin
  2071.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2072.     If @tiHayComa >= 1
  2073.     Begin
  2074.         Select @vchParametro4 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2075.         --Eliminar de la cadena el parametro obtenido
  2076.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2077.     End
  2078.     Else --si no hay coma
  2079.     Begin
  2080.         Select @vchParametro4 = @vchParametro
  2081.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2082.         Select @vchParametro = ''
  2083.     End
  2084. End
  2085.  
  2086. --eliminar los espacios al inicio y al final
  2087. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2088.  
  2089. --Obtener el quinto parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2090. If @vchParametro <> ''
  2091. Begin
  2092.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2093.     If @tiHayComa >= 1
  2094.     Begin
  2095.         Select @vchParametro5 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2096.         --Eliminar de la cadena el parametro obtenido
  2097.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2098.     End
  2099.     Else --si no hay coma
  2100.     Begin
  2101.         Select @vchParametro5 = @vchParametro
  2102.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2103.         Select @vchParametro = ''
  2104.     End
  2105. End
  2106.  
  2107. --eliminar los espacios al inicio y al final
  2108. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2109.  
  2110. --Obtener el sexto parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2111. If @vchParametro <> ''
  2112. Begin
  2113.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2114.     If @tiHayComa >= 1
  2115.     Begin
  2116.         Select @vchParametro6 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2117.         --Eliminar de la cadena el parametro obtenido
  2118.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2119.     End
  2120.     Else --si no hay coma
  2121.     Begin
  2122.         Select @vchParametro6 = @vchParametro
  2123.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2124.         Select @vchParametro = ''
  2125.     End
  2126. End
  2127.  
  2128. --eliminar los espacios al inicio y al final
  2129. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2130.  
  2131. --Obtener el septimo parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2132. If @vchParametro <> ''
  2133. Begin
  2134.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2135.     If @tiHayComa >= 1
  2136.     Begin
  2137.         Select @vchParametro7 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2138.         --Eliminar de la cadena el parametro obtenido
  2139.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2140.     End
  2141.     Else --si no hay coma
  2142.     Begin
  2143.         Select @vchParametro7 = @vchParametro
  2144.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2145.         Select @vchParametro = ''
  2146.     End
  2147. End
  2148.  
  2149. --eliminar los espacios al inicio y al final
  2150. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2151.  
  2152. --Obtener el octavo parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2153. If @vchParametro <> ''
  2154. Begin
  2155.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2156.     If @tiHayComa >= 1
  2157.     Begin
  2158.         Select @vchParametro8 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2159.         --Eliminar de la cadena el parametro obtenido
  2160.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2161.     End
  2162.     Else --si no hay coma
  2163.     Begin
  2164.         Select @vchParametro8 = @vchParametro
  2165.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2166.         Select @vchParametro = ''
  2167.     End
  2168. End
  2169.  
  2170. --eliminar los espacios al inicio y al final
  2171. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2172.  
  2173. --Obtener el noveno parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2174. If @vchParametro <> ''
  2175. Begin
  2176.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2177.     If @tiHayComa >= 1
  2178.     Begin
  2179.         Select @vchParametro9 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2180.         --Eliminar de la cadena el parametro obtenido
  2181.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2182.     End
  2183.     Else --si no hay coma
  2184.     Begin
  2185.         Select @vchParametro9 = @vchParametro
  2186.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2187.         Select @vchParametro = ''
  2188.     End
  2189. End
  2190.  
  2191. --eliminar los espacios al inicio y al final
  2192. Set @vchParametro = ltrim(rtrim(@vchParametro))
  2193.  
  2194. --Obtener el decimo parametro, siempre y cuando la variable <<@vchParametro>> tenga datos
  2195. If @vchParametro <> ''
  2196. Begin
  2197.     Select @tiHayComa = PATINDEX ( '%,%' , @vchParametro )
  2198.     If @tiHayComa >= 1
  2199.     Begin
  2200.         Select @vchParametro10 = substring ( @vchParametro, 1, @tiHayComa - 1 )
  2201.         --Eliminar de la cadena el parametro obtenido
  2202.         Select @vchParametro = substring ( @vchParametro, @tiHayComa + 1, 1000 )
  2203.     End
  2204.     Else --si no hay coma
  2205.     Begin
  2206.         Select @vchParametro10 = @vchParametro
  2207.         --Eliminar de la cadena el parametro obtenido, vacio por que ya no existen más parametros
  2208.         Select @vchParametro = ''
  2209.     End
  2210. End
  2211.  
  2212. --eliminar los espacios al inicio y al final de todos los parametros
  2213. Set @vchParametro1 = ltrim(rtrim(@vchParametro1))
  2214. Set @vchParametro2 = ltrim(rtrim(@vchParametro2))
  2215. Set @vchParametro3 = ltrim(rtrim(@vchParametro3))
  2216. Set @vchParametro4 = ltrim(rtrim(@vchParametro4))
  2217. Set @vchParametro5 = ltrim(rtrim(@vchParametro5))
  2218. Set @vchParametro6 = ltrim(rtrim(@vchParametro6))
  2219. Set @vchParametro7 = ltrim(rtrim(@vchParametro7))
  2220. Set @vchParametro8 = ltrim(rtrim(@vchParametro8))
  2221. Set @vchParametro9 = ltrim(rtrim(@vchParametro9))
  2222. Set @vchParametro10 = ltrim(rtrim(@vchParametro10))
  2223.  
  2224. --Executa el procemiento almacenado dependiendo del parametro enviado
  2225. If isnumeric(@vchParametro1) = 1
  2226. Begin
  2227.     Select @iParametroNum1 = cast(@vchParametro1 as int)
  2228.  
  2229.     Exec sp_ppinGeneraScriptObjeto
  2230.     @iAccion = @iParametroNum1,
  2231.     @vchValor1 = @vchParametro2,
  2232.     @vchValor2 = @vchParametro3,
  2233.     @vchValor3 = @vchParametro4,
  2234.     @vchValor4 = @vchParametro5,
  2235.     @vchValor5 = @vchParametro6,
  2236.     @vchValor6 = @vchParametro7
  2237. End
  2238. Else
  2239. Begin
  2240.     Exec sp_ppinGeneraScriptObjeto
  2241.     @iAccion = 0,
  2242.     @vchValor1 = '',
  2243.     @vchValor2 = '',
  2244.     @vchValor3 = '',
  2245.     @vchValor4 = '',
  2246.     @vchValor5 = '',
  2247.     @vchValor6 = ''
  2248. End
  2249. GO
  2250.  
  2251. If exists ( Select * From sysobjects Where name = 'sp_GenerateConstantScript' )
  2252.     Drop Procedure sp_GenerateConstantScript
  2253. GO
  2254. Create Procedure sp_GenerateConstantScript
  2255. (
  2256.     @FirstId int,
  2257.     @GroupName nvarchar(400),
  2258.     @Names nvarchar(max)
  2259. )
  2260. As
  2261. /*
  2262. ** Purpose:      Obtain the insert/update scripts for a new group of constants
  2263. ** Parameters:   @FirstId: The id used for the first constant id, and also used for the group id
  2264. **               @GroupName: The name of the new group
  2265. **               @Names: Comma separated values of names, with the names and friendly names that the constants will have.
  2266. **                       Any item could be optionally separated into name and friendly name by a "|"
  2267. **                       i.e.: "Open|Connection is open,Closed|Connection is closed"
  2268. **
  2269. ** Usage samples:  
  2270. **  Exec sp_GenerateConstantScript 5000, 'Connection Status', 'Open|Connection is open, Close|Connection is closed, None'
  2271. **  Exec sp_GenerateConstantScript 5100, 'Gender', 'Male,Female'
  2272. ** 
  2273. ** Creation Date: 15/07/2013
  2274. ** Creation User: federicoc
  2275. ** Revision:      0
  2276. */
  2277.  
  2278. Begin
  2279.     Set nocount on
  2280.     Declare @index int, @value nvarchar(max), @name nvarchar(max), @fname nvarchar(max), @script nvarchar(max), @err nvarchar(max),
  2281.             @constantsScript nvarchar(max), @lastCgcId int, @lastCrId int, @cgid int, @constantGroupConstantsScript nvarchar(max), @constantRegionsScript nvarchar(max),
  2282.             @regionId int
  2283.     Declare @newLine CHAR(2) = CHAR(13) + CHAR(10)
  2284.     Declare @constant table ( [Index] int, Value nvarchar(max) )
  2285.     Declare @region table ( id int, ok bit )
  2286.  
  2287.     If exists ( Select * From DEM_DEV..ConstantGroup Where Id = @FirstId )
  2288.     Begin
  2289.         Set @err = N'*** WARNING *** ConstantGroup with id ' + Cast(@FirstId as nvarchar(max)) + ' already exists'
  2290.         RAISERROR (@err, 12, 1);
  2291.     End
  2292.     If exists ( Select * From DEM_DEV..Constant Where Id = @FirstId )
  2293.     Begin
  2294.         Set @err = N'*** WARNING *** Constant with id ' + Cast(@FirstId as nvarchar(max)) + ' already exists'
  2295.         RAISERROR (@err, 12, 1);
  2296.     End
  2297.  
  2298.     Select Top 1 @lastCgcId = Id + 1 From DEM_DEV..ConstantGroupConstant Order by Id Desc
  2299.     Select Top 1 @lastCrId = Id + 1 From DEM_DEV..ConstantRegion Order by Id Desc
  2300.  
  2301.     -- {id}: Constant.Id. {fname}: FriendlyName, {name}: Name, {key}: Key.
  2302.     Declare @scriptConstant nvarchar(max) =
  2303. 'If Exists (Select * From Constant Where [Id] = {id})
  2304.     Update Constant
  2305.     Set [FriendlyName] = N''{fname}'',
  2306.     [Name] = N''{name}'',
  2307.     [Key] = N''{key}'',
  2308.     [Comment] = Null
  2309.     Where [Id] = {id}
  2310. Else
  2311.     Insert Into Constant([Id], [FriendlyName], [Name], [Key], [Comment])
  2312.     Values ({id}, N''{fname}'', N''{name}'', N''{key}'', Null)'
  2313.  
  2314.     -- {id}: ConstantGroup.Id. {name}: Name
  2315.     Declare @scriptConstantGroup nvarchar(max) =
  2316. 'If Exists (Select * From ConstantGroup Where [Id] = {id})
  2317.     Update ConstantGroup
  2318.     Set [Name] = N''{name}''
  2319.     Where [Id] = {id}
  2320. Else
  2321.     Insert Into ConstantGroup([Id], [Name])
  2322.     Values ({id}, N''{name}'')'
  2323.        
  2324.     -- {id}: ConstantGroupConstant.Id. {cgid}: ConstantGroupId, {cid}: ConstantId, {order}: Order.
  2325.     Declare @scriptConstantGroupConstant nvarchar(max) =
  2326. 'If Exists (Select * From ConstantGroupConstant Where [Id] = {id})
  2327.     Update ConstantGroupConstant
  2328.     Set [ConstantGroupId] = {cgid},
  2329.     [ConstantId] = {cid},
  2330.     [Order] = {order},
  2331.     [IsDefault] = 0
  2332.     Where [Id] = {id}
  2333. Else
  2334.     Insert Into ConstantGroupConstant([Id], [ConstantGroupId], [ConstantId], [Order], [IsDefault])
  2335.     Values ({id}, {cgid}, {cid}, {order}, 0)'
  2336.  
  2337.     Declare @scriptConstantRegion nvarchar(max) =
  2338. 'If Exists (Select * From ConstantRegion Where [Id] = {id})
  2339.     Update ConstantRegion
  2340.     Set [ConstantId] = {cid},
  2341.     [RegionId] = {rid}
  2342.     Where [Id] = {id}
  2343. Else
  2344.     Insert Into ConstantRegion([Id], [ConstantId], [RegionId])
  2345.     Values ({id}, {cid}, {rid})'
  2346.  
  2347.     -- ConstantGroup script
  2348.     Set @cgid = @FirstId
  2349.     Set @script = REPLACE(@scriptConstantGroup, '{id}', @cgid)
  2350.     Set @script = REPLACE(@script, '{name}', @GroupName)
  2351.     Print @newLine + @script + @newLine
  2352.  
  2353.     Insert into @constant
  2354.     select [Index], LTRIM(rtrim(value))
  2355.     from DEM_DEV.dbo.fn_Split(@Names, ',')
  2356.    
  2357.     Insert into @region
  2358.     select Id, 0
  2359.     from DEM_DEV..Region
  2360.     Where IsActive = 1
  2361.    
  2362.     Select @constantsScript = '', @constantGroupConstantsScript = '', @constantRegionsScript = ''
  2363.    
  2364.     While exists ( Select * from @constant )
  2365.     Begin
  2366.         Select Top 1 @index = [Index], @value = Value From @constant
  2367.         Select Top 1 @name = [Value] From DEM_DEV.dbo.fn_Split(@value, '|') Order By [Index] Asc
  2368.         Select Top 1 @fname = [Value] From DEM_DEV.dbo.fn_Split(@value, '|') Order By [Index] Desc
  2369.        
  2370.         -- Constant script
  2371.         Set @script = REPLACE(@scriptConstant, '{id}', @FirstId)
  2372.         Set @script = REPLACE(@script, '{fname}', @fname)
  2373.         Set @script = REPLACE(@script, '{name}', @name)
  2374.         Set @script = REPLACE(@script, '{key}', 'K' + CAST(@FirstId as nvarchar(max)))
  2375.        
  2376.         Set @constantsScript = @constantsScript + @newLine + @script + @newLine
  2377.        
  2378.         -- ConstantGroupConstant script
  2379.         Set @script = REPLACE(@scriptConstantGroupConstant, '{id}', @lastCgcId)
  2380.         Set @script = REPLACE(@script, '{cgid}', @cgid)
  2381.         Set @script = REPLACE(@script, '{cid}', @FirstId)
  2382.         Set @script = REPLACE(@script, '{order}', @index + 1)
  2383.        
  2384.         Set @constantGroupConstantsScript = @constantGroupConstantsScript + @newLine + @script + @newLine
  2385.        
  2386.         -- ConstantRegion
  2387.         While exists ( Select * From @region where ok = 0 )
  2388.         Begin
  2389.             Select top 1 @regionId = id from @region where ok = 0
  2390.            
  2391.             Set @script = REPLACE(@scriptConstantRegion, '{id}', @lastCrId)
  2392.             Set @script = REPLACE(@script, '{cid}', @FirstId)
  2393.             Set @script = REPLACE(@script, '{rid}', @regionId)
  2394.            
  2395.             Set @constantRegionsScript = @constantRegionsScript + @newLine + @script + @newLine
  2396.            
  2397.             Set @lastCrId = @lastCrId + 1
  2398.            
  2399.             Update @region Set ok = 1 where id = @regionId
  2400.         End
  2401.    
  2402.         Update @region Set ok = 0
  2403.        
  2404.        
  2405.         Select @FirstId = @FirstId + 1, @lastCgcId = @lastCgcId + 1
  2406.        
  2407.         Delete from @constant Where [Index] = @index
  2408.     End
  2409.  
  2410.     Print @constantsScript + @newLine
  2411.     Print 'Set Identity_insert ConstantGroupConstant On'
  2412.     Print @constantGroupConstantsScript
  2413.     Print 'Set Identity_insert ConstantGroupConstant Off' + @newLine + @newLine
  2414.     Print 'Set Identity_insert ConstantRegion On'
  2415.     Print @constantRegionsScript
  2416.     Print 'Set Identity_insert ConstantRegion Off'
  2417. End
  2418. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement