martes, 5 de agosto de 2014

Otra forma de ejecución controlada de sentencias sql / Another form of controlled execution of sql statements

/*
       Otra forma de ejecucion controlada de sentencias sql
       Another form of controlled execution of sql statements

       Cuando debemos ejecutar gran cantidad de sentencias sql desatendido y debemos recolectar los errores
       When we run unattended lot of sql statements and we collect errors
*/


set NOCOUNT on

DECLARE @SQLCommand  VARCHAR  (2000)
DECLARE @NSQLCommand NVARCHAR (2000)
DECLARE @SQLERROR    INT

declare @TableSQL table (Orden INT IDENTITY , SQL varchar (4000) )
declare @TableSQLErr table ( ErrorNumber int,  ErrorDesc varchar (4000), SQL varchar (4000) )


/*
       En esta seccion insertaremos en la variable tabla @TableSQL todos los scripts que debemos ejecutar,
       aqui un ejemplo de reindexado de tablas

       In this section we will insert into @ table Variable TableSQL all scripts that we run,
       here an example of re-indexing of tables
*/
insert into @TableSQL select 'ALTER INDEX ALL ON ' + name + ' REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON);' from sys.objects where type = 'U'

/********************Se ejecutan todas las sentencias generadas previamente*******************/
DECLARE FKPK_cursor CURSOR FOR
       select SQL from @TableSQL order by orden
  OPEN FKPK_cursor;

 FETCH NEXT FROM FKPK_cursor
   INTO @SQLCommand

  WHILE @@FETCH_STATUS = 0

  BEGIN
       BEGIN TRY
             Set @NSQLCommand = Convert(nvarchar(2000), @SQLCommand)
        --print @NSQLCommand
        EXEC sp_executesql @statement = @NSQLCommand
       END TRY
       BEGIN CATCH
             set @SQLERROR = @@error
             Insert into @TableSQLErr values (@SQLERROR, ERROR_MESSAGE(), @SQLCommand)
       END CATCH;
    FETCH NEXT FROM FKPK_cursor
      INTO @SQLCommand
  END

CLOSE FKPK_cursor;
DEALLOCATE FKPK_cursor;
/*********************************************************************************/

set NOCOUNT OFF

/*
       Resultado: Todas las operaciones ejecutadas
       Result: All transactions executed
 */
Select * from @TableSQL order by orden

/*
       Resultado: Todos errores ocurridos
       Result: All errors
*/

Select * from @TableSQLErr

martes, 20 de diciembre de 2011

One parameter, list of values

/*
Target:
1) Develop a stored procedure where sending a list of values ​​concatenated for space,
bulk insert all records
2) Develop a procedure that receives a list of occurrences can be concatenated by space
bring the possible values

Objetivo:
1) Desarrollar un procedimiento almacenado donde enviando una lista de valores concatenados por espacio,
inserte de forma masiva todos los registros
2) Desarrollar un procedimiento que enviando una lista de ocurrencias concatenadas por espacio puedan
traer los valores posibles

*/




CREATE FUNCTION dbo.fn_ParametersToTable( @ParametrosIn VARCHAR(max))
RETURNS @ParameterTable TABLE ( ParameterValue varchar(50))
AS
BEGIN
/*
Function that can process a parameter and perform a split of the values ​​returned in a table
Funcion que permite procesar un parametro y realizar un split de los valores devolviendolos en una tabla
*/
DECLARE @ParamItem varchar(50)
WHILE CHARINDEX( ' ', @ParametrosIn ) > 0 BEGIN
SET @ParamItem = LOWER( LTRIM(RTRIM( SUBSTRING( @ParametrosIn , 1, CHARINDEX( ' ', @ParametrosIn ) -1))))
SET @ParametrosIn = SUBSTRING( @ParametrosIn , CHARINDEX( ' ', @ParametrosIn ) + 1, len(@ParametrosIn))
IF NOT EXISTS ( SELECT * FROM @ParameterTable WHERE ParameterValue = @ParamItem)
INSERT @ParameterTable ( ParameterValue ) VALUES (@ParamItem)
END
IF LEN(rtrim(@ParametrosIn) ) != '' BEGIN
SET @ParamItem = LOWER( LTRIM(RTRIM( @ParametrosIn )))
IF NOT EXISTS ( SELECT * FROM @ParameterTable WHERE ParameterValue = @ParamItem)
INSERT @ParameterTable ( ParameterValue ) VALUES (@ParamItem )
END
RETURN
END
GO


/*
Sample table to demonstrate the use
Tabla de muestra para demostrar el uso
*/
CREATE TABLE ExampleTbl (field1 int, field2 varchar(20))






GO

CREATE PROCEDURE ExampleInsertList
@ValueList varchar(max)
AS
DECLARE @field1 INT
DECLARE @field2 VARCHAR(20)
/*
Stored procedure taking a single parameter, perform a stock split and inserted into a table

Procedimiento almacenado tomando un solo parametro, realiza un split de valores e inserta en una tabla
*/


INSERT INTO
ExampleTbl
(
field1 ,
field2
)
SELECT
CONVERT(INT, ParameterValue) AS field1,
'Value ' + ParameterValue AS field2
FROM
dbo.fn_ParametersToTable(@ValueList )
GO

/*
Run the test where you insert all the values ​​listed in Table ExampleTbl

Ejecutamos la prueba donde se inserta todos los valores de la lista en la tabla ExampleTbl
*/

EXEC ExampleInsertList @ValueList = '1 2 3 4 5 6 7 8 9 10 11 12 232 4545 125454 5645646 465465 4521 321 2138574 54'

GO

CREATE PROCEDURE ExampleQueryList
@ParameterList VARCHAR(MAX)
AS

/*

Consultation where a list of parameters is the conditional search

Consulta donde una lista de parametros es el condicional de busqueda

*/
SELECT ExampleTbl.* FROM
ExampleTbl
WHERE
field1
IN (
SELECT
CONVERT(INT, ParameterValue)
FROM
dbo.fn_ParametersToTable(@ParameterList )
)

GO

/*
Query Execution of example with lists

Ejecucion del ejemplo de Query con listas
*/
EXEC ExampleQueryList @ParameterList = '1 12 232'


/*

They now have a circuit with all the suggestions of using the function fn_ParametersToTable if your taste and utility can donate what he deems necessary and will be rewarded in many more post

Ahora tienen un circuito con todas las sugerencias del uso de la funcion fn_ParametersToTable si es de su gusto y utilidad puede donar lo que crea conveniente y serà retribuido en muchos mas post

*/

viernes, 24 de junio de 2011

Database Text to NVARCHAR

/*

This time the problem we faced was: passed all existing TEXT fields in a database field NVARCHAR (MAX).

EASY, enjoy!

En esta oportunidad el problema a resolver era: pasar todos los campos TEXT existentes en una base de datos en campos NVARCHAR(MAX).

Sensillo, enjoy!


Nota: Este script puede dañar la integridad de la base, cualquier daño que provoque será bajo su responsabilidad .

Note: This script can damage the integrity of the base, causing damage thatwill be your responsibility.

*/

DECLARE @CMD VARCHAR(255)

DECLARE @TABLENAME VARCHAR(255)

DECLARE @COLUMNNAME VARCHAR(255)

--Well here declare a cursor, only that

DECLARE Table_cursor CURSOR FOR

--Make the cmd line to be executed

SELECT

'ALTER TABLE ' + O.NAME + ' ALTER COLUMN ' + C.NAME + ' NVARCHAR(MAX) NULL' AS CMD,

O.NAME AS TABLENAME,

C.NAME AS COLUMNNAME

FROM

SYS.OBJECTS AS O

INNER JOIN

SYS.COLUMNS AS C

ON (C.OBJECT_ID = O.OBJECT_ID)

INNER JOIN

SYS.TYPES AS T

ON( T.SYSTEM_TYPE_ID = C.SYSTEM_TYPE_ID )

WHERE

TYPE = 'U' AND C.SYSTEM_TYPE_ID = 35

--Open the cursor

OPEN Table_cursor

--Fetch the first

FETCH NEXT FROM Table_cursor

--Use the field values in the declared vars

INTO @CMD, @TABLENAME, @COLUMNNAME

--LOOP NOT EOF

WHILE @@FETCH_STATUS = 0

BEGIN

PRINT REPLICATE('=',255)

PRINT 'TABLE:' + @TABLENAME

PRINT 'COLUMN:' + @COLUMNNAME

PRINT ''

PRINT 'EXECUTING => ' + @CMD

EXEC (@CMD) --here execute the command

PRINT 'DONE '

--Move next :P

FETCH NEXT FROM Table_cursor

INTO @CMD, @TABLENAME, @COLUMNNAME

--End of cursor

END

--Close an Deallocate cursor

CLOSE Table_cursor

DEALLOCATE Table_cursor

Print replicate('=',255)

jueves, 7 de octubre de 2010

DB Source control

/*

This post is a example of source control on sql databases, You can modify, extend or cut the functions of the next script, ask and discuss, The author is not responsible of content, only for educational purposes.

*/

/*Create a table where save every change on DB */

CREATE TABLE DEVSQLControl (

[ID] INT IDENTITY(1,1) ,

[Name] VARCHAR(256) ,

[Type] CHAR(2) ,

Create_date DATETIME ,

Modify_date DATETIME ,

DataCheckSum BIGINT ,

stamp TIMESTAMP ,

SnapDate DATETIME

)

/*

Insert in to DEVSQLControl table the new changes, including what I want to seek, you are free to change the list to your wish

*/

INSERT INTO

DEVSQLControl

(

[Name] ,

[type] ,

Create_date ,

Modify_date ,

DataCheckSum ,

SnapDate

)

SELECT

O.name ,

O.type ,

O.create_date ,

O.modify_date ,

BINARY_CHECKSUM(

O.name,

O.object_id,

O.principal_id,

O.schema_id,

O.parent_object_id,

O.type,

O.type_desc,

O.create_date,

O.modify_date,

O.is_ms_shipped,

O.is_published,

O.is_schema_published

) ,

Getdate()

FROM

SYS.OBJECTS AS O

INNER JOIN

DEVSQLControl AS DV

ON(-- 1 = 1

O.name COLLATE DATABASE_DEFAULT = DV.name COLLATE DATABASE_DEFAULT

AND O.type COLLATE DATABASE_DEFAULT = DV.type COLLATE DATABASE_DEFAULT

)

WHERE O.TYPE

IN ( 'U','P','fn', 'C ','PK','UQ','F ', 'D ' )

AND DataCheckSum <> BINARY_CHECKSUM(

O.name,

O.object_id,

O.principal_id,

O.schema_id,

O.parent_object_id,

O.type,

O.type_desc,

O.create_date,

O.modify_date,

O.is_ms_shipped,

O.is_published,

O.is_schema_published

)

GROUP BY

O.name ,

O.type ,

O.create_date ,

O.modify_date ,

BINARY_CHECKSUM(

O.name,

O.object_id,

O.principal_id,

O.schema_id,

O.parent_object_id,

O.type,

O.type_desc,

O.create_date,

O.modify_date,

O.is_ms_shipped,

O.is_published,

O.is_schema_published

)