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)