Mostrando entradas con la etiqueta SQL Server. Mostrar todas las entradas
Mostrando entradas con la etiqueta SQL Server. Mostrar todas las entradas

sábado, 20 de junio de 2015

Waiting while executing query in SQL Server

-- Example using adventurework database

WAITFOR DELAY '00:00:10'
 BEGIN
     SELECT
         p.ProductID,
         p.Name
     FROM Production.Product AS p
 END

WHILE in SQL Server

-- Example using AdventureWork Database

-- Sentencia WHILE

 BEGIN TRAN
     WHILE (SELECT MAX(p.ListPrice) FROM Production.Product AS p) < 5000
     BEGIN
         UPDATE Production.Product
         SET
             ListPrice = ListPrice * 2
            
         SELECT MAX(p.ListPrice) FROM Production.Product AS p
        
         IF (SELECT MAX(p.ListPrice) FROM Production.Product AS p) > 12000
         BEGIN
             SELECT 'Salimos'
             BREAK
         END
     END
 ROLLBACK TRAN

CASE in SQL Server

-- Simple CASE sentence using AdventureWork Database

-- CASE simple. Evaluamos un parametro.

 SELECT
     d.DepartmentID,
     d.Name,
     d.GroupName,
     CASE d.GroupName
         WHEN 'Research and Development' THEN 'Cuarto A'
         WHEN 'Sales and Marketing' THEN 'Cuarto B'
         WHEN 'Manufacturing' THEN 'Cuarto C'
         ELSE 'Cuarto D'
     END AS Tipo_Cuarto
 FROM HumanResources.Department AS d

 DECLARE @valor INT = 0
 SELECT
     d.DepartmentID,
     d.Name,
     d.GroupName,
     CASE
         WHEN d.Name = 'Research and Development' AND @valor = 1 THEN 'Cuarto A'
         WHEN d.Name = 'Sales' OR d.DepartmentID = 4 THEN 'Cuarto B'
         WHEN d.Name LIKE 'T%' THEN 'Cuarto C'
         ELSE 'Cuarto D'
     END AS Tipo_Cuarto
 FROM HumanResources.Department AS d

IF Sentence in SQL Server

-- Example about IF sentence using AdventureWork Database

DECLARE @SeleccionQuery INT = 1;

 IF(@SeleccionQuery = 1 OR @SeleccionQuery = 3) AND NOT @SeleccionQuery IS NULL
 BEGIN
     SELECT
         p.ProductID,
         p.Name,
         p.Color
     FROM Production.Product AS p
     WHERE p.Color = 'Red'
     ORDER BY p.Name
 END
 ELSE
 BEGIN
     SELECT
         p.ProductID,
         p.Name,
         p.Color
     FROM Production.Product AS p
     WHERE p.Color = 'Black'
     ORDER BY
         p.Name
 END

Pagination in SQL Server

-- Example using AdventureWorks Database

-- Paginación.

 /*
     Actualmente se maneja desde la aplicación; pero lo mejor es desde el servidor.
 */

 SELECT
     ProductID,
     Name
 FROM Production.Product
 ORDER BY Name
 OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

 SELECT
     ProductID,
     Name
 FROM Production.Product
 ORDER BY Name
 OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;

 SELECT
     ProductID,
     Name
 FROM Production.Product
 ORDER BY Name
 OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

 DECLARE @pagina INT

 SET @pagina = (SELECT COUNT(*) / 10 FROM Production.Product AS p)

 SELECT
     p.ProductID,
     p.Name
 FROM Production.Product AS p
 WHERE p.Color = 'Red'
 ORDER BY
     p.Name
 OFFSET 0 ROWS FETCH NEXT @pagina ROWS ONLY

sábado, 8 de noviembre de 2014

SQL Server Database Test


create database planificacion
go

use planificacion
go

create table universidad
(
idUniversidad int identity(1,1) primary key not null,
nombre varchar(50) not null,
lema varchar(100) not null,
fechaFundacion date not null,
autorizacionCNU varchar(50) not null,
mision varchar(250) not null,
vision varchar(250) not null
)
go

create table deptoNic
(
idUbicacion int identity(1,1) primary key not null,
ubicacion varchar(45) not null
)
go

-- drop table recintos

create table recintos
(
idRecinto int identity(1,1) primary key not null,
recinto varchar(45) not null,
nomb_abreviado varchar(45) not null,
idUbicacion int not null,
direccion varchar(45) not null,
idUniversidad int not null,
constraint fk_ubicacion_recintos foreign key(idUbicacion)
references deptoNic(idUbicacion)
on delete no action on update no action,
constraint fk_universidad_recintos foreign key(idUniversidad)
references universidad(idUniversidad)
on delete no action on update no action
)
go

-- drop table edificios

create table edificios
(
idEdificio int identity(1,1) primary key not null,
edificio varchar(45) not null,
idRecinto int not null,
constraint fk_recinto_edificios foreign key(idRecinto)
references recintos(idRecinto)
on delete no action on update no action
)
go

create table facultades
(
idFacultad int identity(1,1) primary key not null,
facultad varchar(50) not null,
descripcion varchar(50),
idRecinto int not null,
constraint fk_recinto_facultades foreign key(idRecinto)
references recintos(idRecinto)
on delete no action on update no action
)
go

create table aulas
(
idAula int identity(1,1) primary key not null,
aula varchar(45) not null,
idEdificio int not null,
constraint fk_edificio_aulas foreign key(idEdificio)
references edificios(idEdificio)
on delete no action on update no action
)
go

create table carreras
(
idCarrera int identity(1,1) primary key not null,
carrera varchar(50) not null,
descripcion varchar(50),
perfil varchar(100) not null,
duracion varchar(50) not null,
idFacultad int not null,
constraint fk_facultad_carreras foreign key(idFacultad)
references facultades(idFacultad)
on delete no action on update no action
)
go

create table grupos
(
idGrupo int identity(1,1) primary key not null,
annoLectivo int not null,
idCarrera int not null,
annoAcademico varchar(50) not null,
semestre varchar(2) not null,
cantAlumnos int not null,
grupo varchar(50) not null,
constraint fk_carrera_grupos foreign key(idCarrera)
references carreras(idCarrera)
on delete no action on update no action
)
go

create table laboratorios
(
idLab int identity(1,1) primary key not null,
nomLab varchar(45) not null,
puestosTrab int not null,
idCarrera int not null,
constraint fk_carrera_laboratorios foreign key(idCarrera)
references carreras(idCarrera)
on delete no action on update no action
)
go

create table deptoAcad
(
idDepto int identity(1,1) primary key not null,
departamento varchar(45) not null,
descripcion varchar(45),
idCarrera int not null,
constraint fk_carrera_deptoAcad foreign key(idCarrera)
references carreras(idCarrera)
on delete no action on update no action
)
go

create table asignaturas
(
idAsignatura int identity(1,1) primary key not null,
asignatura varchar(50) not null,
horasPlan int not null,
horasPlanificacion int not null,
frecuencia int not null,
horasLab int not null
)
go

create table flujograma
(
idCarrera int not null,
anno varchar(3) not null,
semestre varchar(2) not null,
idAsignatura int not null,
constraint fk_carrera_flujograma foreign key(idCarrera)
references carreras(idCarrera)
on delete no action on update no action,
constraint fk_asignatura_flujograma foreign key(idAsignatura)
references asignaturas(idAsignatura)
on delete no action on update no action
)
go

create table categoria
(
idCategoria int identity(1,1) primary key not null,
categoria varchar(45) not null,
salarioBase int not null
)
go

create table tipoContrato
(
idTipo int identity(1,1) primary key not null,
tipoContrato varchar(45) not null,
cantidadHoras int not null
)
go

-- drop table docentes

create table docentes
(
idDocente int identity(1,1) primary key not null,
nombres varchar(45) not null,
apellidos varchar(45) not null,
fechaNac date not null,
sexo varchar(1) not null,
direccion varchar(45) not null,
telefono varchar(45) not null,
celular varchar(45) not null,
email varchar(45) not null,
idDepto int not null,
idCategoria int not null,
idTipoContrato int not null,
docentescol varchar(45) not null,
constraint fk_dpto_academico_docentes foreign key(idDepto)
references deptoAcad(idDepto)
on delete no action on update no action,
constraint fk_categoria_docentes foreign key(idCategoria)
references categoria(idCategoria)
on delete no action on update no action,
constraint fk_tipo_docentes foreign key(idTipoContrato)
references tipoContrato(idTipo)
on delete no action on update no action
)
go

create table turnos
(
idTurno int identity(1,1) primary key not null,
turno varchar(45) not null,
descripcion varchar(45)
)
go

-- drop table planificacion

create table planificacion
(
idPlan int identity(1,1) primary key not null,
anoLectivo int not null,
semestre varchar(5) not null,
idTurno int not null,
idGrupo int not null,
idAula int not null,
idAsignatura int not null,
idDia int not null,
idHorario int not null,
idDocente int not null,
idLab int not null,
observaciones varchar(45),
constraint fk_turno_planificacion foreign key(idTurno)
references turnos(idTurno)
on delete no action on update no action,
constraint fk_grupo_planificacion foreign key(idGrupo)
references grupos(idGrupo)
on delete no action on update no action,
constraint fk_aula_planificacion foreign key(idAula)
references aulas(idAula)
on delete no action on update no action,
constraint fk_asignatura_planificacion foreign key(idAsignatura)
references asignaturas(idAsignatura)
on delete no action on update no action,
constraint fk_docente_planificacion foreign key(idDocente)
references docentes(idDocente)
on delete no action on update no action,
constraint fk_laboratorio_planificacion foreign key(idLab)
references laboratorios(idLab)
on delete no action on update no action
)
go

martes, 2 de julio de 2013

SQL Server To PostgreSQL


Descargar la siguiente librería:

1) SQL Server Driver

2) PostgreSQL Driver

3) SQLServerToPostgreSQLDemo.jar

/**************************************************************************/

import jfrodriguez.miclases.SQLServerToPostgreSQLDemo;

public class SQLToPSQL
{
    SQLServerToPostgreSQLDemo clon = new SQLServerToPostgreSQLDemo();
   
    public SQLToPSQL()
    {
        clon.ConectarSQLServer("server", "database", "user", "password");
        clon.ConectarPostgreSQLServer("server", "database", "user", "password");
       
        clon.ClonarTabla("schema", "table");
       
        clon.CerrarConexion();
    }
   
    public static void main(String[] args)
    {
        SQLToPSQL hcm = new SQLToPSQL();
    }
}

/**************************************************************************/
 

Library to migrate data from SQL Server to PostgreSQL

Descargar la librería en el siguiente enlace:

Library to migrate data from SQL Server to PostgreSQL


viernes, 14 de junio de 2013

SQL Server and PostgreSQL Connection using Java


/*

Descargar las librerías de conexión para

SQL Server

PostgreSQL

*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConexionJavaSQL
{
    Connection conPSQL = null;
    Connection conSQL = null;
   
    //Constructor
    public  ConexionJavaSQL()
    {
        this.ConectarSQLServer("servidor", "base", "usuario", "clave");
        this.ConectarPostgreSQLServer("servidor", "base", "usuario", "clave");
       
        // Consulta de prueba
       
        this.ConsultarSQL("SELECT COUNT(*) FROM tabla t;");
    }
   
    public void ConectarSQLServer(String servidor, String base, String usuario, String clave)
    {
        try
        {
            try
            {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            }
            catch(ClassNotFoundException e)
            {
                System.out.println("No se encontró el Driver para SQL Server");
            }
           
            String connectionUrl = "jdbc:sqlserver://" + servidor +
                    ";database=" + base + ";integratedSecurity=false;" +
                    "user=" + usuario + ";password=" + clave;
            conSQL = DriverManager.getConnection(connectionUrl);
           
            if(conSQL != null)
                System.out.println("Conexión satisfactoria a SQL Server");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
   
    public void ConectarPostgreSQLServer(String servidor, String base, String usuario, String clave)
    {
        try
        {
            try
            {
                Class.forName("org.postgresql.Driver");
            }
            catch(ClassNotFoundException e)
            {
                System.out.println("No se encontró el Driver para PostgreSQL");
            }
           
            conPSQL = DriverManager.getConnection("jdbc:postgresql://" + servidor +
                    ":5432/" + base, usuario, clave);
           
            if(conPSQL != null)
                System.out.println("Conexión satisfactoria a PostgreSQL");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
   
    public void CerrarConexion(Connection con)
    {
        try
        {
            con.close();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
   
    public Object[] ConsultarSQL(String query)
    {
        Statement s = null;
        ResultSet rs = null;
       
        int k = 0;
       
        try
        {
            s = conSQL.createStatement();
            rs = s.executeQuery(query);
           
            while(rs.next())
            {
                System.out.println(rs.getString(1));
               
                k++;
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
       
        return null;
    }
   
    public static void main(String []args)
    {
        ConexionJavaSQL m = new ConexionJavaSQL();
    }
}

/********** El éxito de la vida es la entrega total a Dios **********/

miércoles, 12 de junio de 2013

SQL Server Driver para Java

sqljdbc4.jar

"El éxito de la vida está en la entrega total a Dios"

SQL Server Connection using Python in Ubuntu

1) Descargar el driver para SQL Server

2) Descomprimir el archivo descargado, clic derecho extraer...

3) Abrir una terminal Ctrl + Alt + t

4) cd Descargas/pyodbc-3.0.3

5) sudo apt-get install build-essential

6) sudo python setup.py build

7) sudo python setup.py install

"Dejar un comentario es una forma de agradecimiento"

sábado, 4 de agosto de 2012

Order SQL Query


Consulta SQL: Resultado SQL:

miércoles, 8 de febrero de 2012

Encriptación

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER FUNCTION [dbo].[myencrypt](@phrase VARCHAR(100),
                      @action VARCHAR(1))
RETURNs varchar(200) aS

begin

declare
    @longitud int,
    @i int,
    @phrase_dkrpt VARCHAR(200),
    @phrase_dkrpt_temp VARCHAR(200)

    set @i = 1
    set @longitud = 0
    set @phrase_dkrpt = ''
    set @phrase_dkrpt_temp = ''
   

    select @longitud = len(@phrase)
    while @i <= @longitud
     begin
        IF (@action = 'E')
           begin
            SELECT @phrase_dkrpt_temp = char(Ascii(SUBSTRing(@phrase,@i,1))+64)
           end
         else
           begin
               if (@action = 'D')
               begin
                    SELECT @phrase_dkrpt_temp = char(Ascii(SUBSTRing(@phrase,@i,1))-64)
               end
           end

        select @phrase_dkrpt = @phrase_dkrpt + @phrase_dkrpt_temp
        set @i = @i + 1
        ---select @phrase_dkrpt = @phrase_dkrpt + cast(@i as varchar)
     end

    RETURN @phrase_dkrpt

end

Numeros a Letras

CREATE PROCEDURE sp_numero_a_letras
    @monto NUMERIC(14, 2),
    @moneda CHAR(10),
    @letras CHAR(255) OUTPUT
AS
BEGIN
    DECLARE @unidades      CHAR(255),
            @decenas       CHAR(255),
            @centenas      CHAR(255),
            @especiales    CHAR(108),
            @decimales     CHAR(25),
            @valor_entero  CHAR(9),
            @longitud      INT,
            @caracteres    CHAR(3),
            @contador      INT,
            @posicion      INT,
            @flag          INT,
            @decimal       INT
   
    SET NOCOUNT ON
    SELECT @unidades = 'un    dos   tres  cuatro' +
           'cinco seis  siete ocho  ' +
           'nueve '
   
    SELECT @especiales = 'once        doce        trece       ' +
           'catorce     quince      diez y seis ' +
           'diez y sietediez y ocho diez y nueve'
   
    SELECT @decenas = 'diez     veinte   treinta  cuarenta ' +
           'cincuentasesenta  setenta  ochenta  ' +
           'noventa  '
   
    SELECT @centenas = 'ciento       doscientos   trescientos  cuatrocientos' +
           'quinientos   seiscientos  setecientos  ochocientos  ' +
           'novecientos  '
   
    SELECT @decimal = (@monto - CAST(@monto AS INT)) * 100
    SELECT @monto = ROUND(@monto, 0, 1)
    SELECT @longitud = LEN(RTRIM(CAST(CAST(@monto AS INT) AS CHAR)))
    SELECT @valor_entero = RTRIM(CAST(CAST(@monto AS INT) AS CHAR))
    SELECT @valor_entero = REPLICATE('0', 9 -@longitud) + SUBSTRING(@valor_entero, 1, @longitud)
    SELECT @contador = 1,
           @letras = REPLICATE(' ', 255)
   
    WHILE @contador < 8
    BEGIN
        /* 0 */
        SELECT @caracteres = SUBSTRING(@valor_entero, @contador, 3)
        IF @caracteres <> '000'
        BEGIN
            /* 1 */
            IF SUBSTRING(@caracteres, 1, 1) <> '0'
               -- CENTENAS
            BEGIN
                /* 2 */
                SELECT @posicion = CAST(SUBSTRING(@caracteres, 1, 1) AS INT)
                IF @posicion = '1'
                   AND CAST(SUBSTRING(@caracteres, 2, 2) AS INT) = 0
                BEGIN
                    /* 3 */
                   
                    SELECT @letras = RTRIM(@letras) +
                           ' Cien '
                END/* 3 */
                ELSE
                BEGIN
                    /* 4 */
                    SELECT @letras = RTRIM(@letras) +
                           ' ' +
                           SUBSTRING(@centenas, 13 * (@posicion - 1) + 1, 13)
                END /* 4 */
            END /* 2 */
            SELECT @flag = 0
            IF CAST(SUBSTRING(@caracteres, 2, 2) AS INT) > 10
               AND CAST(SUBSTRING(@caracteres, 2, 2) AS INT) < 20
                   -- ESPECIALES
            BEGIN
                /* 5 */
                SELECT @posicion = CAST(SUBSTRING(@caracteres, 3, 1) AS INT)
                SELECT @letras = RTRIM(@letras) +
                       ' ' +
                       SUBSTRING(@especiales, 12 * (@posicion - 1) + 1, 12)
               
                SELECT @flag = 1
            END /* 5 */
            IF @flag = 0
               -- DECENAS
            BEGIN
                /* 6 */
                IF SUBSTRING(@caracteres, 2, 1) <> '0'
                BEGIN
                    /* 7 */
                    SELECT @posicion = CAST(SUBSTRING(@caracteres, 2, 1) AS INT)
                    IF @posicion <> 2
                       OR SUBSTRING(@caracteres, 3, 1) = '0'
                    BEGIN
                        /* 8 */
                        SELECT @letras = RTRIM(@letras) +
                               ' ' +
                               SUBSTRING(@decenas, 9 * (@posicion - 1) + 1, 9)
                    END/* 8 */
                    ELSE
                    BEGIN
                        /* 9 */
                       
                        SELECT @letras = RTRIM(@letras) +
                               ' veinti'
                    END /* 9 */
                END /* 7 */
               
                IF SUBSTRING(@caracteres, 3, 1) <> '0'
                  
                   -- UNIDADES
                BEGIN
                    /* 10 */
                    SELECT @posicion = CAST(SUBSTRING(@caracteres, 3, 1) AS INT)
                    IF SUBSTRING(@caracteres, 2, 1) <> '0'
                       AND SUBSTRING(@caracteres, 3, 1) <> '0'
                    BEGIN
                        /* 11 */
                        IF SUBSTRING(@caracteres, 2, 1) = '2'
                            SELECT @letras = RTRIM(@letras) +
                                   SUBSTRING(@unidades, 6 * (@posicion - 1) + 1, 6)
                        ELSE
                            SELECT @letras = RTRIM(@letras) +
                                   ' y ' +
                                   SUBSTRING(@unidades, 6 * (@posicion - 1) + 1, 6)
                    END/* 11 */
                    ELSE
                        SELECT @letras = RTRIM(@letras) +
                               ' ' +
                               SUBSTRING(@unidades, 6 * (@posicion - 1) + 1, 6)
                END/* 10 */
            END /* 6 */
            IF @contador = 1
            BEGIN
                /* 12 */
                IF @posicion = 1
                   AND SUBSTRING(@caracteres, 1, 2) = '00'
                BEGIN
                    /* 13 */
                    SELECT @letras = RTRIM(@letras) +
                           ' millón '
                END/* 13 */
                ELSE
                    --    if @posicion = 1
                BEGIN
                    /* 14 */
                   
                    SELECT @letras = RTRIM(@letras) +
                           ' millones '
                END /* 14 */
            END/* 12 */
            ELSE
            BEGIN
                /* 15 */
                IF @contador = 4
                BEGIN
                    /* 16 */
                    SELECT @letras = RTRIM(@letras) +
                           ' mil '
                END/* 16 */
            END /* 15 */
        END /* 1 */
        SELECT @contador = @contador + 3
    END /* 0 */
    -- CIENTOS
    IF RIGHT(RTRIM(@letras), 6) = 'ciento'
    BEGIN
        /* 17 */
        SELECT @letras = SUBSTRING(@letras, 1, LEN(RTRIM(@letras)) -6) +
               'cien '
    END /* 17 */
    -- DECIMALES
    IF @decimal > 0
        SELECT @decimales = '  ' + @moneda + ' con ' +
               REPLICATE('0', 2 - LEN(RTRIM(LTRIM(CAST(@decimal AS CHAR(2))))))
               +
               LTRIM(RTRIM(CAST(@decimal AS CHAR(2)))) +
               '/100'
    ELSE
        SELECT @decimales = '  ' + @moneda + ' exactos'
    -- FINAL
    SELECT @letras = '** ' +
           RTRIM(SUBSTRING(@letras, 1, 255)) +
           RTRIM(@decimales) +
           ' **'
   
    SELECT 'letras' = UPPER(@letras)
END

Eliminar palabras repetidas de una fila


CREATE FUNCTION delete_repeated_words
(
    @word VARCHAR(300)
)
RETURNS VARCHAR(300)
AS
BEGIN
    DECLARE @new_word VARCHAR(300),
    @ultimate_word VARCHAR(300),
    @k INT,
    @b INT
   
    SET @word = LTRIM(@word)
   
    SET @ultimate_word = ''
    SET @new_word = ''
   
    WHILE(CHARINDEX(' ', LTRIM(@word)) <> 0)
    BEGIN
        SET @k = CHARINDEX(' ', LTRIM(@word))

        SET @new_word = LEFT(LTRIM(@word), @k)
       
        SET @b = CHARINDEX(@new_word, @ultimate_word)

        IF(@b = 0)
            SET @ultimate_word = @ultimate_word + @new_word
           
        SET @word = SUBSTRING(LTRIM(@word), @k + 1, LEN(LTRIM(@word)))
    END

    SET @new_word = LEFT(LTRIM(@word), @k)
       
        SET @b = CHARINDEX(@new_word, @ultimate_word)

        IF(@b = 0)
            SET @ultimate_word = @ultimate_word + @new_word

    RETURN @ultimate_word
END