Compartilhando conhecimento com o mundo

Com tecnologia do Blogger.

Pesquisa

Download

Blogger Tricks

Blogger Themes

Visitas

Assuntos

Mostrar mensagens com a etiqueta SQL Server. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta SQL Server. Mostrar todas as mensagens

2/28/2020

Migrando o Informix para o SQL Server


Tem vários programas para migrar o Informix para o SQL Server, a grande maioria pagos, mas encontrei um bem interessante (e código aberto) e resolvei compartilhar com vocês - O SQLines Data é uma ferramenta de transferência de dados, escalável e de alto desempenho, conversão de esquema e validação para a migração de vários bancos de dados. A ferramenta requer conexões com os bancos de dados Informix (ODBC/CLI sem ODBC Manager) e SQL Server (SQL Server Native Client).

Validando e depois transferindo os dados





Comparando a quantidade de linhas de cada tabelas de um banco com outro (bateu)

3/07/2015

Compactando Pasta do Servidor - SSIS


Este é um exemplo de um programa feito pelo SSIS que faz backup de algumas pastas importantes do servidor. Este procedimento pelo SSIS faz o backup de algumas pastas (retirando algumas pastas que não quero), compactando, colocando o arquivo compactado em uma pasta especifica e fazendo um controle da quantidade de arquivos compactados. Primeiro, vamos criar uma tabela onde vai ficar armazenado as pasta que vamos usar. Download Clique Aqui

1 - Criando a Tabela

Definindo uma tabela onde vamos inserir os caminhos das pastas, dá para colocar nas variaveis as pastas o problema é que no futuro uma mudança no nome dos servidores ou no nome das pastas temos que editar cada uma das variaveis no SSIS e alterar na unha o nome das pastas, colocando em uma tabela é só rodar um simples update resolve, o nome da tabela vai ser bdfaz_programas;
CREATE TABLE [dbo].[bdfaz_programas](
 [prg_codigo] [int] NOT NULL,
 [prg_descricao] [varchar](60) NOT NULL,
 [prg_sigla] [varchar](20) NULL,
 [prg_nome_detalhado] [varchar](100) NULL,
 [prg_sistema_origem] [varchar](60) NOT NULL,
 [prg_analista_origem] [varchar](60) NOT NULL,
 [prg_fone_origem] [varchar](9) NOT NULL,
 [prg_email_origem] [varchar](60) NOT NULL,
 [prg_job_grande_porte] [varchar](60) NULL,
 [prg_area_grande_porte] [varchar](60) NULL,
 [prg_nome_arquivo_texto] [varchar](60) NULL,
 [prg_origem_inicial] [varchar](60) NULL,
 [prg_origem_final] [varchar](60) NULL,
 [prg_destino_inicial] [varchar](60) NULL,
 [prg_destino_final] [varchar](60) NULL,
 [prg_nome_arquivo_compactado] [varchar](60) NULL,
 [prg_servidor_carga] [varchar](60) NULL,
 [prg_servidor_banco] [varchar](60) NULL,
 [prg_banco_dados] [varchar](60) NULL,
 [frequencia] [varchar](40) NULL,
 [prg_observacao] [varchar](max) NULL
) 
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Este vai ser o registro que vamos inserir que contem os dados sobre as pastas que vamos salvar;
INSERT INTO [dbo]. [bdfaz_programas]
           ([prg_codigo]
           ,[prg_descricao]
           ,[prg_sigla]
           ,[prg_nome_detalhado]
           ,[prg_sistema_origem]
           ,[prg_analista_origem]
           ,[prg_fone_origem]
           ,[prg_email_origem]
           ,[prg_job_grande_porte]
           ,[prg_area_grande_porte]
           ,[prg_nome_arquivo_texto]
           ,[prg_origem_inicial]
           ,[prg_origem_final]
           ,[prg_destino_inicial]
           ,[prg_destino_final]
           ,[prg_nome_arquivo_compactado]
           ,[prg_servidor_carga]
           ,[prg_servidor_banco]
           ,[prg_banco_dados]
           ,[frequencia]
           ,[prg_observacao])
     VALUES
(
   '1',                             --- prg_codigo
   'Compacta_gql',                  --- prg_descricao
   '',                              --- prg_sigla
   'Compacta Pasta',                --- prg_nome_detalhado
   'XXXXX',                         --- prg_sistema_origem
   'Equipe BI',                     --- prg_analista_origem
   '9999-9999',                     --- prg_fone_origem
   'meu_e_mail@alguma.coisa.br',    --- prg_email_origem
   'NULL',                          --- prg_job_grande_porte
   'NULL',                          --- prg_area_grande_porte
   '',                              --- prg_nome_arquivo_texto
   'C:\Claudemar\CARGA\FONTES\',    --- prg_origem_inicial  --- pasta fonte
   'C:\Claudemar\CARGA\TMP',        --- prg_origem_final    --- pasta temporaria
   'C:\Claudemar\CARGA\BACKUP',     --- prg_destino_inicial --- pasta backup (sem \)
   'C:\Claudemar\CARGA\BACKUP\',    --- prg_destino_final   --- pasta backup (com \)
   'modelos_gql_compactados.zip',   --- prg_nome_arquivo_compactado
   'NULL',                          --- prg_servidor_carga
   'NULL',                          --- prg_servidor_banco
   'NULL',                          --- prg_banco_dados
   'mensal',                        --- frequencia
   'NULL'                           --- prg_observacao
)
2 - Variáveis

Abrindo o SSIS vamos definir essas variaveis;
+-----------------------------+---------------+-------------------------+
| nome                        | Data Type     | Value                   |
+-----------------------------+---------------+-------------------------+
| caminho_backup_dois_gql     | String        | caminho_backup_dois_gql |
| caminho_backup_gql          | String        |                         |
| caminho_fonte_gql           | String        | caminho_fonte_gql       |
| caminho_pasta_tmp           | String        | caminho_pasta_tmp       |
| compactar_arquivos          | String        | N                       |
| pasta_modelo_gql            | String        | pasta_modelo_gql        |
| pastas_modelos_gql          | Objet         | System.Object           |
| prg_codigo                  | Int32         | 1                       |
| prg_periodo                 | String        | 15                      |
+-----------------------------+---------------+-------------------------+
O valor da variavel prg_codigo é o mesmo valor que foi colocado no insert acima;

Tela do SSIS das variáveis;



3 - Configurando a Conexão OLE DB

Neste passo vamos apontar no SSIS o banco/tabela onde criamos a tabela acima;



4 - Pelo SSIS

Vamos abrir o SSIS e vamos criar um componente Data Flow (Data Flow Task), depois de adicionar vamos clicar duas vezes nele para acessar o Control Flow, dai vamos adicionar dentro dele dois componentes;

- OLE BD Source e o;
- Script Task (Transformation)

4.1 - OLE BD Source - Script Transformation



4.2 - OLE BD Source

Vamos pegar no banco os valores da tabela que fizemos o insert;

SQL command text
SELECT [prg_codigo]
  ,[prg_origem_inicial] as caminho_fonte_gql
  ,[prg_origem_final] as caminho_pasta_tmp
  ,[prg_destino_inicial] as  caminho_backup_dois_gql
  ,[prg_destino_final] as caminho_backup_gql
  ,[prg_nome_arquivo_compactado] as nome_arquivo_zip
  ,[prg_nome_arquivo_texto]
FROM [dbo].[bdfaz_programas]
WHERE   prg_codigo= ?
Clique em Parameters e adicione a variavel User::prg_codigo



4.3 - Script Transformation

Ele vai gravar as variáveis que estão no banco (do nosso insert) para gravar nas variáveis do nosso SSIS;



ReadWriteVariables marque essas variaveis
User::caminho_backup_dois_gql,User::caminho_backup_gql,User::caminho_fonte_gql,User::caminho_pasta_tmp,User::pasta_modelo_gql
Em (Edit Script) cole o script abaixo - vai gravar nas variaveis os dados (nomes das pastas) que inserimos na tabela;
/* Microsoft SQL Server Integration Services Script Component

*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Windows.Forms;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent

{
    string caminho_backup_gql       = string.Empty;
    string caminho_backup_dois_gql  = string.Empty;
    string caminho_fonte_gql        = string.Empty;
    string caminho_pasta_tmp        = string.Empty;
    string pasta_modelo_gql         = string.Empty;
    //string caminho_processar = string.Empty;

    public override void PreExecute()
    {
        base.PreExecute();
    }

    public override void PostExecute()
    {
        base.PostExecute();

        Variables.caminhofontegql       = caminho_fonte_gql;
        Variables.caminhobackupdoisgql  = caminho_backup_dois_gql;
        Variables.caminhobackupgql      = caminho_backup_gql;
        Variables.caminhopastatmp       = caminho_pasta_tmp;
        Variables.pastamodelogql        = string.Empty;

        // ---------------------------------------------------------------------------------------------
        // Imprimi na tela as variaveis carregadas
        // ---------------------------------------------------------------------------------------------
        //MessageBox.Show(Variables.caminhofontegql, "caminho_fonte_gql");
        //MessageBox.Show(Variables.caminhopastatmp, "caminho_pasta_tmp");
        //MessageBox.Show(Variables.caminhofontedoisgql, "caminho_fonte_dois_gql");
        //MessageBox.Show(Variables.caminhobackupgql, "caminho_backup_gql");
        //MessageBox.Show(Variables.pastamodelogql, "pastamodelogql");
        // ---------------------------------------------------------------------------------------------

    }
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        caminho_fonte_gql = Row.caminhofontegql;
        caminho_pasta_tmp = Row.caminhopastatmp;
        caminho_backup_dois_gql = Row.caminhobackupdoisgql;
        caminho_backup_gql = Row.caminhobackupgql + DateTime.Now.ToString("yyyyMMddHHmmss_") + Row.nomearquivozip;
     }
}
5 - Adicionando um Script Task - Data Flow

No Data Flow vamos criar um componente - Script Task (Transformation)



ReadOnlyVariables marque essas variaveis
User::caminho_fonte_gql,User::caminho_pasta_tmp
Em (Edit Script) cole o script abaixo - este script descobre o nome das pastas e inicia a copia das pastas (tem uma parte que que colocamos algumas pastas para não copiar);
#region Help:  Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
 * a .Net application within the context of an Integration Services control flow. 
 * 
 * Expand the other regions which have "Help" prefixes for examples of specific ways to use
 * Integration Services features within this script task. */
#endregion


using System;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ST_34ad99c71d8c4458afb662e9cd553c03
{
    /// 

    /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    /// or parent of this class.
    /// 

    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */

        #endregion

        #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion

        #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion

        static string CONST_ORIGEM = null;
        static string CONST_DESTINO = null;
        //List lista_origem = new List(); //um arraymultidimensional
        //List lista_destino = new List();

        List lista_origem = new List(); //um arraymultidimensional
        List lista_destino = new List();


        /// 

        /// This method is called when this script task executes in the control flow.
        /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        /// To open Help, press F1.
        /// 

        public void Main()
        {

            //            CONST_ORIGEM = Dts.Variables["prg_origem_inicial_gql"].Value.ToString();
            //            CONST_DESTINO = Dts.Variables["prg_origem_final_gql"].Value.ToString();

            CONST_ORIGEM = Dts.Variables["caminho_fonte_gql"].Value.ToString();
            CONST_DESTINO = Dts.Variables["caminho_pasta_tmp"].Value.ToString() + "\\";

            //descobre o nome das pastas
            ListaDiretorios();

            //executa copia
            for (int i = 0; i < lista_origem.Count; i++)
            {
                CopiaDiretorio(lista_origem[i], lista_destino[i], true);
            }

        }

        #region ListaDiretorios
        void ListaDiretorios()
        {

            // buscar pastas dos modelos GQL

            List lista = new List();

            //List lista = new List();
            string[] dirs = System.IO.Directory.GetDirectories(CONST_ORIGEM);
            //string pasta_suporte_gql = CONST_ORIGEM + "\\suporte_gql";
            //string pasta_suporte_gql = CONST_ORIGEM + "\\DfsrPrivate";


            //lista de nome das pastas (limpa string do caminho completo da past)
            for (int i = 0; i < dirs.LongLength; i++)
            {
                //if (!dirs[i].Contains("suporte"))
                if (
                    //-----------------------------------------------------------------------
                    // 3 pastas que não quero que sejam copiadas para a tmp
                    //-----------------------------------------------------------------------
                    !dirs[i].Contains("DfsrPrivate") &&
                    !dirs[i].Contains("instalacao_gql") &&
                    !dirs[i].Contains("__DFSR_DIAGNOSTICS_TEST_FOLDER__")
                    )

                //if (!dirs[i].Contains("DfsrPrivate"))
                {
                    lista.Add(dirs[i].Replace(CONST_ORIGEM, ""));
                }
            }

            //monta caminho completo da origem
            foreach (string p in lista)
            {
                lista_origem.Add(CONST_ORIGEM + p);


                //--------------------------------------------------------------------------
                // Mensagem das pastas de origem
                //--------------------------------------------------------------------------    
                //MessageBox.Show("Origem " + CONST_ORIGEM + p);
            }

            //monta caminho completo do destino
            foreach (string p in lista)
            {
                lista_destino.Add(CONST_DESTINO + p);


                //--------------------------------------------------------------------------
                // Mensagem das pastas de origem
                //--------------------------------------------------------------------------    
                //MessageBox.Show("Destino " + CONST_DESTINO + p);
            }

        }
        #endregion ListaDiretorios

        #region CopiaFolderSubfolder
        /// 

        /// Metodo para copiar folders e subfolders
        /// 

        /// pasta de origem
        /// pasta de destino
        /// indica se eh para copiar subdiretorios
        private static void CopiaDiretorio(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirName);
            }

            // If the destination directory doesn't exist, create it. 
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destDirName, file.Name);
                file.CopyTo(temppath, false);
            }

            // If copying subdirectories, copy them and their contents to new location. 
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    CopiaDiretorio(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
        #endregion  CopiaFolderSubfolder

    }
}
Imagens



6 - Adicionando o Execute Process Task

No Data Flow vamos criar colocar o Execute Process Task - Este processo vai compactar a pasta temporaria;



Em > Process
RequireFullFileName                  - True
Executable                           - C:\Program Files\WinRAR\Rar.exe
Arguments                            - a -df -ep1 -m5 + caminho_pasta_tmp
FailTaskIfReturnCodeIsNotSucessValue - True
SucessValue                          - 0
TimeOut                              - 0
Em > Arguments > Adicione
"a -df -ep1 -m5 " + @[User::caminho_backup_gql]   + " " +   @[User::caminho_pasta_tmp]
7 - Adicionando o Script Task

No Data Flow vamos adicionar o Script Task (Transformation) - esta parte vai deletar os arquivos compactados antigos - vou deixar somente os 12 últimos arquivos compactados, surgindo mais um novo o arquivo mais antigo será deletado;



ReadOnlyVariable
User::caminho_backup_dois_gql,User::prg_periodo
Em (Edit Script) cole o script abaixo;
/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.

* Este script deleta o arquivo mais antigo do backup compactado da s371
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;

namespace ST_bb39ea0d414d46bbbe9be76558ec7188.csproj
{
    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        /*
            The execution engine calls this method when the task executes.
            To access the object model, use the Dts property. Connections, variables, events,
            and logging features are available as members of the Dts property as shown in the following examples.

            To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
            To post a log entry, call Dts.Log("This is my log text", 999, null);
            To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

            To use the connections collection use something like the following:
            ConnectionManager cm = Dts.Connections.Add("OLEDB");
            cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

            Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
            
            To open Help, press F1.
      */

        public void Main()
        {


            //----------------------------------------------------------------------------
            //Display da variavel da pasta que vamos deletar
            //----------------------------------------------------------------------------
            //MessageBox.Show(Dts.Variables["User::caminho_backup_dois_gql"].Value.ToString());
            
            int RetentionPeriod = Convert.ToInt32(Dts.Variables["User::prg_periodo"].Value.ToString());
            string directoryPath = Dts.Variables["User::caminho_backup_dois_gql"].Value.ToString();
            //string directoryPath = Dts.Variables["User::prg_pasta_backup"].Value.ToString();
            string[] oldfiles = System.IO.Directory.GetFiles(directoryPath, "*.*");
            foreach (string currFile in oldfiles)
            {
                FileInfo currFileInfo = new FileInfo(currFile);
                
                //================================================================================
                //abaixo deleta os arquivos pela data de criacao 
                //================================================================================
                
                if (currFileInfo.CreationTime < (DateTime.Now.AddDays(-RetentionPeriod)))
                
                //================================================================================
                //abaixo deleta os arquivos pela data de modificacao
                //================================================================================
                //if (currFileInfo.LastWriteTime < (DateTime.Now.AddDays(-RetentionPeriod)))
                //================================================================================
                {
                    currFileInfo.Delete();
                }
            }

            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}
8 - Rodando o Projeto

Rodando para ver;

11/26/2014

Que delimitador usar - Informix


Nesse artigo, o objetivo é apresentar uma sugestão envolvendo o problema de descobrir que delimitador usar em uma tabela do informix que parece que usa todos as letras/símbolos, vamos descobrir qual é a letra/simbolo que na tabela do informix menos usa, o backup é de uma tabela do Informix e restauração vai ser no SQL Server 2014.

Umas das soluções foi pesquisar no arquivo do backup da tabela do Informix e ver se tem alguma letra/simbolo disponivel, primeiro vamos preparar o script que vamos rodar o backup da tabela - o backup via external tables que é o backup mais rápido aqui pra mim;

Criar este script com o nome backup_script.sql
#!/bin/sh
###############################################################################
#   Script para backup de tabelas via EXTERNAL TABLES                         #
#   Criado Por Claudemar Martins de Sa                                        #
#   Uso: backup_script.sh [DATABASE] [TABELA]                                 #
#   Rodar: ./backup_script.sql nome_do_banco nome_da_tabela                   #
###############################################################################

DATABASE=${1}
TABLE=${2}

dbaccess ${DATABASE} >/dev/null << EOF
set pdqpriority 30;
CREATE EXTERNAL TABLE informix.bkp_${TABLE}
SAMEAS ${TABLE}
USING
   (DATAFILES ("DISK:/export/home/informix/backup/${TABLE}.unl"),
FORMAT 'DELIMITED',
DELIMITER '',
RECORDEND '',
Deluxe,
NUMROWS 50,
MAXERRORS 50,
REJECTFILE ''
);

insert into bkp_${TABLE}
select * from ${TABLE};

drop table bkp_${TABLE}
EOF
Rodando o backup da tabela sem o delimitador - rodamos assim - ./nome_do_script nome_do_banco nome_da_tabela
./backup_script.sql faz_sgf notes_rel_baixa

Database selected.

PDQ Priority set.

Table created.

9992 row(s) inserted.

Table dropped.

Database closed.
Script que vamos analisar o backup e ver se tem alguma letra que podemos usar como delimitador

Criar este script com o nome delimitador.sql
# :%s/antes/nova/g

TABLE=${1}

echo "q - $(cat $TABLE | grep '\q' | wc -l)" ; 
echo "w - $(cat $TABLE | grep '\w' | wc -l)" ; 
echo "e - $(cat $TABLE | grep '\e' | wc -l)" ; 
echo "r - $(cat $TABLE | grep '\r' | wc -l)" ; 
echo "t - $(cat $TABLE | grep '\t' | wc -l)" ; 
echo "y - $(cat $TABLE | grep '\y' | wc -l)" ; 
echo "u - $(cat $TABLE | grep '\u' | wc -l)" ; 
echo "i - $(cat $TABLE | grep '\i' | wc -l)" ; 
echo "o - $(cat $TABLE | grep '\o' | wc -l)" ; 
echo "p - $(cat $TABLE | grep '\p' | wc -l)" ; 
echo "a - $(cat $TABLE | grep '\a' | wc -l)" ; 
echo "s - $(cat $TABLE | grep '\s' | wc -l)" ; 
echo "d - $(cat $TABLE | grep '\d' | wc -l)" ; 
echo "f - $(cat $TABLE | grep '\f' | wc -l)" ; 
echo "g - $(cat $TABLE | grep '\g' | wc -l)" ; 
echo "h - $(cat $TABLE | grep '\h' | wc -l)" ; 
echo "k - $(cat $TABLE | grep '\k' | wc -l)" ; 
echo "l - $(cat $TABLE | grep '\l' | wc -l)" ; 
echo "z - $(cat $TABLE | grep '\z' | wc -l)" ; 
echo "x - $(cat $TABLE | grep '\x' | wc -l)" ; 
echo "c - $(cat $TABLE | grep '\c' | wc -l)" ; 
echo "v - $(cat $TABLE | grep '\v' | wc -l)" ; 
echo "b - $(cat $TABLE | grep '\b' | wc -l)" ; 
echo "n - $(cat $TABLE | grep '\n' | wc -l)" ; 
echo "m - $(cat $TABLE | grep '\m' | wc -l)" ; 
echo ", - $(cat $TABLE | grep '\,' | wc -l)" ; 
echo ". - $(cat $TABLE | grep '\.' | wc -l)" ; 
echo "; - $(cat $TABLE | grep '\;' | wc -l)" ; 
echo "! - $(cat $TABLE | grep '\!' | wc -l)" ; 
echo "@ - $(cat $TABLE | grep '\@' | wc -l)" ; 
echo "# - $(cat $TABLE | grep '\#' | wc -l)" ; 
echo "$ - $(cat $TABLE | grep '\$' | wc -l)" ; 
echo "% - $(cat $TABLE | grep '\%' | wc -l)" ; 
echo "& - $(cat $TABLE | grep '\&' | wc -l)" ; 
echo "* - $(cat $TABLE | grep '\*' | wc -l)" ; 
echo "( - $(cat $TABLE | grep '(' | wc -l)" ; 
echo ") - $(cat $TABLE | grep ')' | wc -l)" ; 
echo "_ - $(cat $TABLE | grep '\_' | wc -l)" ; 
echo "- - $(cat $TABLE | grep '\-' | wc -l)" ; 
echo "+ - $(cat $TABLE | grep '\+' | wc -l)" ; 
echo "| - $(cat $TABLE | grep '\|' | wc -l)" ; 
echo "~ - $(cat $TABLE | grep '\~' | wc -l)" ; 
echo "? - $(cat $TABLE | grep '\?' | wc -l)" ;
echo "[ - $(cat $TABLE | grep '\[' | wc -l)" ;
echo "] - $(cat $TABLE | grep '\]' | wc -l)" ;
echo "< - $(cat $TABLE | grep '\<' | wc -l)" ;
echo "> - $(cat $TABLE | grep '\>' | wc -l)" ;
echo "{ - $(cat $TABLE | grep '\{' | wc -l)" ;
echo "} - $(cat $TABLE | grep '\}' | wc -l)" ;
echo -n '" - '  
cat $TABLE | grep '"' | wc -l
Rodando o programa para descobrir que letra não existe no arquivo de backup da tabela, reparem o { não tem - vou usar ele como delimitador
./delimitador.sh notes_rel_baixa.unl 

q - 8079
w - 24779
e - 19215
r - 19246
t - 17554
y - 11
u - 17609
i - 17987
o - 19566
p - 14714
a - 18981
s - 18458
d - 18332
f - 13783
g - 10093
h - 6551
k - 136
l - 18383
z - 4793
x - 8326
c - 16933
v - 13901
b - 24779
n - 19679
m - 16356
, - 13836
. - 20762
; - 1238
! - 7
@ - 1
# - 0
$ - 1364
% - 228
& - 21
* - 19
( - 1832
) - 2457
_ - 6
- - 18013
+ - 30
| - 47306
~ - 5
? - 7
[ - 1
] - 4
< - 24779
> - 24779
{ - 0
} - 1
" - 233
Alterando o arquivo de backup e colocando a letra { como delimitador
#!/bin/sh
###############################################################################
#   Script para backup de tabelas via EXTERNAL TABLES                         #
#   Criado Por Claudemar Martins de Sa                                        #
#   Uso: backup_script.sh [DATABASE] [TABELA]                                 #
#   Rodar: ./backup_script.sql nome_do_banco nome_da_tabela                   #
###############################################################################

DATABASE=${1}
TABLE=${2}

dbaccess ${DATABASE} >/dev/null << EOF
set pdqpriority 30;
CREATE EXTERNAL TABLE informix.bkp_${TABLE}
SAMEAS ${TABLE}
USING
   (DATAFILES ("DISK:/export/home/informix/backup/${TABLE}.unl"),
FORMAT 'DELIMITED',
DELIMITER '{',
RECORDEND '',
Deluxe,
NUMROWS 50,
MAXERRORS 50,
REJECTFILE ''
);

insert into bkp_${TABLE}
select * from ${TABLE};

drop table bkp_${TABLE}
EOF
Rodando o backup da tabela no Informix
./backup_script.sql faz_sgf notes_rel_baixa

Database selected.

PDQ Priority set.

Table created.

9992 row(s) inserted.

Table dropped.

Database closed.
Criando a tabela no SQL Server 2014 igual como esta no Informix
use faz_sgf;

create table "dbo".notes_rel_baixa 
  (
    osn_codigo integer not null ,
    rel_versao integer not null ,
    inscricaoestadual decimal(14,0) not null ,
    baixa_dt_ini_fisc datetime2,
    baixa_dt_fin_fisc datetime2,
    baixa_folha varchar(10),
    baixa_rudfto varchar(8),
    baixa_dt_conclusao datetime2,
    baixa_descritivo text,
    baixa_altcadastral text,
    baixa_versaosf varchar(1,1),
    baixa_sit_aprovacao integer not null ,
    usr_codigo_criacao integer not null ,
    usr_dt_hr_criacao datetime2 ,
    usr_codigo_alter integer,
    usr_dt_hr_alter datetime2,
    primary key (osn_codigo,rel_versao,inscricaoestadual)
  );
O utilitário bcp é uma ferramenta de linha de comandos que usa a API do BCP (Programa de cópia em massa).
bcp bdfaz_faz_sgf.dbo.notes_rel_baixa format nul -c -f D:\Usuários\faz_sgf\notes_rel_baixa.fmt -T -S s905\itc005 -t "{"
Ficou assim;
11.0
16
1       SQLCHAR             0       12      "{"      1     osn_codigo                                 ""
2       SQLCHAR             0       12      "{"      2     rel_versao                                 ""
3       SQLCHAR             0       41      "{"      3     inscricaoestadual                          ""
4       SQLCHAR             0       30      "{"      4     baixa_dt_ini_fisc                          ""
5       SQLCHAR             0       30      "{"      5     baixa_dt_fin_fisc                          ""
6       SQLCHAR             0       10      "{"      6     baixa_folha                                SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       8       "{"      7     baixa_rudfto                               SQL_Latin1_General_CP1_CI_AS
8       SQLCHAR             0       30      "{"      8     baixa_dt_conclusao                         ""
9       SQLCHAR             0       0       "{"      9     baixa_descritivo                           SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       0       "{"      10    baixa_altcadastral                         SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       1       "{"      11    baixa_versaosf                             SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       12      "{"      12    baixa_sit_aprovacao                        ""
13      SQLCHAR             0       12      "{"      13    usr_codigo_criacao                         ""
14      SQLCHAR             0       30      "{"      14    usr_dt_hr_criacao                          ""
15      SQLCHAR             0       12      "{"      15    usr_codigo_alter                           ""
16      SQLCHAR             0       30      "{\n"    16    usr_dt_hr_alter                            ""
Coloco no servidor SQL Server os arquivos de bcp e o arquivo de backup da tabela no Informix - rodando este comando;
use faz_sgf;

BULK INSERT notes_rel_baixa --- delimitador ({)
FROM 'I:\data\bdfaz\carga_claudemar\faz_sgf\notes_rel_baixa.unl' -- unload
WITH (FORMATFILE = 'I:\data\bdfaz\carga_claudemar\faz_sgf\notes_rel_baixa.fmt'); -- bcp
Terminou ok a importação no SQL Server
(9992 row(s) affected)