Postagens

Mostrando postagens com o rótulo SQL

Tempo em ano, mês, dia, horas entre 2 datas

1: GO 2: SET QUOTED_IDENTIFIER ON 3: GO 4: -- ============================================= 5: -- Author: Angelo Carlotto 6: -- Create date: 09/04/2012 7: -- Description: 8: -- Esta função retorna um texto descrevendo o total de tempo entre duas datas 9: -- O usuário pode escolher dentre ano,mes,dia,hora,min e seg quais parcelas deseja que sejam exibidas 10: -- Caso o parametro @hasAno=0 e @hasMes=1, caso @ano=2 e @mes=1, neste caso a string retornara será: 25 mes(s) 11: -- ============================================= 12: ALTER FUNCTION GetStringDescreveTotalTempoEntreDatas 13: ( 14: @dataInicial DATETIME , 15: @dataFinal DATETIME , 16: @hasAno BIT , 17: @hasMes BIT , 18: @hasDia BIT , 19: @hasHora BIT , 20: @hasMinuto BIT , 21: @hasSegundo BIT 22: ) 23: RETURNS VARCHAR ( MAX ) 24: AS 25: BEGIN 26: DECLAR...

Auditoria utilizando SQL Server

/* Alterar somente o nome da dataBase */   use GrandeSeletor   /** * A TRIGGER DE AUDITORIA NÃO FUNCIONA PARA OS SEGUINTES TIPOS: * 1 - TEXT, * 2 - NTEXT, * 3 - IMAGE */   SET NOCOUNT ON --Verifica se existe uma tabela com o nome PowerAuditoria, se não existir criamos a tabela. if not exists ( SELECT name FROM SYSOBJECTS WHERE type = 'U' AND name = 'PowerAuditoria' ) begin create table PowerAuditoria( Id int not null identity (1,1) primary key , Usuario varchar (10) not null , DataHora datetime not null , Tabela varchar (50) not null , AcaoExecutada char (1) not null , RegistroAnterior varchar (3500), RegistroAtual varchar (3500) ) end   Declare @idTabela int , @nameTabela varchar (20), @nameColuna varchar (50), @query varchar (8000), @tipoCampo varchar (100), @tamanhoCampo int , @auxdeclare va...

Visualizar descrição de tabelas e colunas do MSSQL

1: SELECT 2: u.name + '.' + t.name AS [Tabela], 3: td. value AS [Descrição da Tabela], 4: c.name AS [Coluna], 5: cd. value AS [Descrição da Coluna] 6: FROM sysobjects t 7: INNER JOIN sysusers u ON u.uid = t.uid 8: LEFT OUTER JOIN sys.extended_properties td ON td.major_id = t.id 9: AND td.minor_id = 0 AND td.name = 'MS_Description' 10: INNER JOIN syscolumns c ON c.id = t.id 11: LEFT OUTER JOIN sys.extended_properties cd ON cd.major_id = c.id 12: AND cd.minor_id = c.colid AND cd.name = 'MS_Description' 13: WHERE t.type = 'u' 14: ORDER BY t.name, c.colorder

Função Split no SQL - retornando uma tabela.

1: CREATE FUNCTION [dbo].[Split] 2: ( 3: @text varchar (8000), 4: @delimiter varchar (1) = ' ' 5: ) 6: RETURNS @Strings TABLE ( 7: position int IDENTITY PRIMARY KEY , 8: value varchar (8000) 9: ) 10: AS 11: BEGIN 12: DECLARE @ index int 13: SET @ index = -1 14: WHILE (LEN(@text) > 0) 15: BEGIN 16: SET @ index = CHARINDEX(@delimiter , @text) 17: IF (@ index = 0) AND (LEN(@text) > 0) 18: BEGIN 19: INSERT INTO @Strings VALUES (@text) 20: BREAK 21: END 22: IF (@ index = 1) 23: BEGIN 24: INSERT INTO @Strings VALUES ( LEFT (@text, @ index - 1)) 25: SET @text = RIGHT (@text, (LEN(@text) - @ index )) 26: END 27: ELSE 28: SET @text = RIGHT (@text, (LEN(@text) - @ index...

Retornar uma tabela passando uma array

CREATE FUNCTION GetTableFromArray ( @text varchar (8000), @delimiter varchar (20) = ' ' ) RETURNS @Strings TABLE ( position int IDENTITY PRIMARY KEY , value varchar (8000) ) AS BEGIN   DECLARE @ index int SET @ index = -1 WHILE (LEN(@text) > 0) BEGIN SET @ index = CHARINDEX(@delimiter , @text) IF (@ index = 0) AND (LEN(@text) > 0) BEGIN INSERT INTO @Strings VALUES (@text) BREAK END IF (@ index > 1) BEGIN INSERT INTO @Strings VALUES ( LEFT (@text, @ index - 1)) SET @text = RIGHT (@text, (LEN(@text) - @ index )) END ELSE SET @text = RIGHT (@text, (LEN(@text) - @ index )) END RETURN END

Arredondar valor decimal

CREATE FUNCTION Arredondar(@valor decimal (18,2)) RETURNS DECIMAL AS BEGIN DECLARE @retValor DECIMAL (18,2), @ real DECIMAL (18,2), @ dec DECIMAL (18,2), @tot DECIMAL (18,2) SET @retValor =0 SET @ real = Floor(@valor) SET @ dec = Abs(@valor) SET @tot = @ dec - @ real   IF (@tot = 0.5) BEGIN SET @retValor = @valor END ELSE BEGIN IF (@tot > 0.5) BEGIN SET @retValor = Floor(@valor) + 1 END IF (@tot < 0.5) BEGIN SET @retValor = Floor(@valor) END END RETURN @retValor END       -- TESTANDO -- SELECT dbo.Arredondar(7.58)   -- RESULTADO -- 8.00

Trabalhando com zeros antes dos numeros

//Trabalhando com 2 casas no sql right ( '00' + convert ( varchar , [variavel]), 2)

Função SQL que retorna valor (R$) por extenso

Retirado do site.: http://eltonbicalho.blogspot.com/2010/01/escrever-um-valor-por-extenso- sql .html CREATE FUNCTION dbo.Extenso(@VALOR DECIMAL (18, 5)) RETURNS VARCHAR (255) AS BEGIN DECLARE @STR_EXT VARCHAR (255), @FLAG_E INT , @GRUPO DECIMAL (10, 2), @MOEDA VARCHAR (10), @MOEDA_PLURAL VARCHAR (10), @FLAG_CENTAVOS DECIMAL (18, 5) -- Aqui vc podera configurar a descricao da Moeda SET @MOEDA = 'Real' SET @MOEDA_PLURAL = 'Reais' SET @FLAG_CENTAVOS = 1 -- Exibir os centavos [ 0) Nao 1) Sim ] SET @STR_EXT = '' SET @FLAG_E = 0 SET @GRUPO = 0 IF (( CONVERT ( INT , @VALOR) - ( CONVERT ( INT , @VALOR) % 1)) = 0) BEGIN SET @STR_EXT = ' Zero' END ELSE BEGIN DECLARE @TEMPINT BIGINT SET @TEMPINT = .000001*(( CONVERT ( INT , @VALOR) % 1000000000) - ( CONVERT ( INT , @VALOR) % 1000000)) SELECT @FLAG_E = FLAG_E, @STR_EXT = STR_EXT FROM dbo.TrataGrupoExtenso( @TEMPINT, ' Milhão' , ' Milhões' , @FLAG_E, @STR_EXT) SET @TEMPINT = .00...

Funcão SQL para abreviar nomes

CREATE FUNCTION dbo.Abrevia ( @nome varchar (200) ) RETURNS varchar (25) AS BEGIN declare @aux varchar (120) declare @aux2 varchar (25) declare @fim varchar (25)   --Pegar o primeiro nome set @fim= left (@nome,charindex( ' ' ,@nome)) set @aux=@fim --Inicializa variável set @aux2= '' --Inicializa variável --Enquanto tem nomes do meio while len(@aux)>0 begin --pega primeiro nome set @aux= left (@nome,charindex( ' ' ,@nome)) --remove primeiro nome set @nome=ltrim(replace(@nome,@aux, '' )) --exclui de,da,dos(da silva, dos santos..) if charindex( ' ' ,@nome)>4 begin --Abrevia com . set @aux2=@aux2+ substring (@nome,1,1)+ '. ' end end --concatena tudo(primeiro nome+abreviações+último select @fim=@fim+@aux2+@nome nome) RETURN ( @fim ) END

Retornando Registros Aleatórios no Access, SQL Server e MySql

1:   2: /** 3: *Registro aleatório no * 4: *ID é o campo de indentificação de sua tabela. 5: */ 6:   7: SELECT * FROM tabela order by Rnd( Int (Now()*[ID])-Now()*[ID]); 8:   9: /** 10: *Registro aleatório no MySQL: 11: */ 12:   13: SELECT * FROM tabela order by RAND(); 14:   15: /** 16: *Registro aleatório no SQL Server: 17: */ 18:   19: SELECT * FROM tabela order by NEWID();

Trabalhar com tabelas de Databases diferentes

SELECT * FROM OPENDATASOURCE ( 'SQLOLEDB' , 'Data Source=localhost; Tag with column collation when possible=True; User ID=usuario; Password=senha' ).[NameDataBase].[dbo].[NameTable] P

Gerar arquivos diário de backup do sql

declare @caminho varchar (100) declare @nomeArquivo varchar (100) declare @caminhoCompleto varchar (100) declare @ database varchar (20) declare @nomeBackup varchar (20) set @caminho = N 'c:\' set @nomeArquivo = convert ( varchar ,getdate(),102) set @caminhoCompleto = @caminho + @nomeArquivo set @ database = 'suaDatabase' set @nomeBackup = 'nomeDoSeuBackup' Backup database [@ database ] to disk = @caminhoCompleto WITH INIT , NOUNLOAD , NAME = @nomeBackup , NOSKIP , STATS = 10, NOFORMAT

Trabalhando com Cursores no SQLServer

Imagem

Retorna valor usando Store procedure

protected string retornaValor(int ra, string campo_a_retornar) { valor_retorno = null; SqlDataReader dr; SqlCommand cmd = new SqlCommand("SP_RETORNA_ALUNO_PARAM_RA_DCE", conexao()); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Ra", SqlDbType.Int).Value = ra; cmd.Connection.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { valor_retorno = dr[campo_a_retornar].ToString().Trim(); } cmd.Connection.Close(); dr.Close(); return valor_retorno; }

Altera os dados de uma tabela usando uma procedure

protected bool Alterar(int seq) { try { SqlCommand cmd = new SqlCommand("SP_ALTERA_TB_DELPHI_ALUNOS_DCE", conexao()); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Ra", SqlDbType.Char, 10).Value = txtra.Text.ToUpper(); cmd.Parameters.Add("@Nome", SqlDbType.Char, 70).Value = txtNome.Text.ToUpper(); cmd.Parameters.Add("@Num_chamada", SqlDbType.Char, 2).Value = txtNChamada.Text; cmd.Parameters.Add("@Sala", SqlDbType.Char, 4).Value = txtSala.Text; cmd.Parameters.Add("@Ano", SqlDbType.Char, 4).Value = txtAno.Text; cmd.Parameters.Add("@Seq", SqlDbType.Int).Value = seq; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); return true; } catch (SqlException ex) { return false; } ...

Retorna registro do bd

public string retorna_valor(SqlConnection conn, String sql, String campo_a_retornar) { valor_retorno = null; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { valor_retorno = dr[campo_a_retornar].ToString().Trim(); } conn.Close(); dr.Close(); return valor_retorno; }

Altera registro no bd

public Boolean alterar(SqlConnection conn, String strsql) { try { conn.Open(); SqlCommand exec = new SqlCommand(strsql, conn); exec.ExecuteNonQuery(); return true; } catch (SqlException ex) { return false; } finally { conn.Close(); } }

Deleta registro no bd

public Boolean deletar(SqlConnection conn, String strsql) { try { conn.Open(); SqlCommand exec = new SqlCommand(strsql, conn); exec.ExecuteNonQuery(); return true; } catch (SqlException ex) { return false; } finally { conn.Close(); } }

Consultar no bd

public Boolean consultar(SqlConnection conn, String strsql) { SqlCommand cmd = new SqlCommand(strsql, conn); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); conn.Close(); return true; } else { conn.Close(); return false; } }

Inserir no bd

public Boolean inserir_bd(SqlConnection conn, String strsql) { try { conn.Open(); SqlCommand exec = new SqlCommand(strsql, conn); exec.ExecuteNonQuery(); return true; } catch (SqlException t) { return false; } finally { conn.Close(); } }