Category Archives: SQL Server

ASP.Net SQL Server

Como utilizar o Response.Redirect para uma nova janela

Para fazer um redireccionamento para uma nova janela podemos adicionar ao controlo <asp:button> o atributo

ButtonPrint.Attributes.Add(“OnClick”, “javascript:window.open(‘novapagina.aspx’)”)

este atributo pode ser adicionado no Page.load()

SQL Server

SQL Server: Duplicação de registos indexados

———————————————————————-
— Carlos Galhano 2009.02.05
— Duplicação de Registos indexados
–tab teste: testeid,titulo
–tab teste2: teste2id,titulo2,testeid
———————————————————————-
Alter table teste add oldid integer
———————————————————————-
Select TesteID, Titulo INTO #tmpteste FROM teste
go
insert into teste (Titulo,oldid) (Select Titulo,testeid from #tmpteste)
go

—————–
Select teste.TesteID, teste2.Titulo2 INTO #tmpteste2 FROM teste2 inner join teste on teste.oldid=teste2.testeid
go
—————–
insert into teste2 (Titulo2,testeID)
((Select Titulo2,testeid from #tmpteste2 ))
go
—————–
drop table #tmpteste
go
drop table #tmpteste2
go
—————–
Alter table teste drop column oldid
———————————————————————-

Code Snippets ASP.Net 2.0 SQL Server

Configurações para começar a utilizar WebParts

Para começar a usar Webparts é necessário ter uma base de dados de suporte.

Para criar essa base de dados é necessários executar a aplicação aspnet_reqsql.exe que se encontra no directorio do .Net framework, normalmente C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

Depois é necessário dar permissões a um utilizador para aceder à base de dados criada, no SQLServer.

Estando o SQL preparado necessitamos de criar as ligações no nosso webSite:

no ficheiro web.config devemos criar uma nova connection (por exemplo):

<connectionStrings>
<add name=”connASPNETDB” connectionString=”Server=MEUSERVER; Database=ASPNETDB; User Id=MEUUSER;Password=USERPASS;” providerName=”System.Data.SqlClient” />
</connectionStrings>

e definir o sqlpersonalization provider :

<webParts>
<personalization defaultProvider=”AspNetSqlPersonalizationProvider”>
<providers>
<clear/>
<add name=”AspNetSqlPersonalizationProvider”
type=”System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”
connectionStringName=”connASPNETDB” />
</providers>
</personalization>
</webParts>

e bem-vindo ao mundo das webparts 🙂

SQL Server

LINQPad

Tired of querying in antiquated SQL?

Well, you don’t have to! LINQPad lets you interactively query SQL databases in a modern query language: LINQ. Kiss goodbye to SQL Management Studio!

LINQPad supports everything in C# 3.0 and Framework 3.5:

  • LINQ to SQL
  • LINQ to Objects
  • LINQ to XML

LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from my book, C# 3.0 in a Nutshell. There’s no better way to experience the coolness of LINQ and functional programming.

And LINQPad is more than just a LINQ query tool: it’s a code snippet IDE. Instantly execute any C# 3 or VB 9 expression or statement block!

Best of all, LINQPad is free and needs no installation: just download and run. The executable is only 2MB and is self-updating.

website: http://www.linqpad.net/

Linux SQL Server Utils

FreeTDS

FreeTDS is a set of libraries for Unix and Linux that allows your programs to natively talk to Microsoft SQL Server and Sybase databases.

Technically speaking, FreeTDS is an open source implementation of the TDS (Tabular Data Stream) protocol used by these databases for their own clients. It supports many different flavors of the protocol and three APIs to access it. Additionally FreeTDS works with other software such as Perl and PHP, providing access from those languages as well.

If you are looking for a Java implementation, we refer you to the jTDS project on SourceForge.

FreeTDS has many possible uses. It has been used by Unix/Linux webservers to present data stored in SQL Server to the web, to port SQL Server database code from NT to Unix, to import data into SQL Server from a Unix source, and to provide database access on platforms (such as realtime systems) that have no native drivers.

The FreeTDS C libraries are available under the terms of the GNU LGPL license, consult the COPYING.LIB file in the distribution for details.

Homepage

SQL Server

DBCC SHRINKFILE

Como usar o comando DBCC SHRINKFILE para reduzir o tamanho do log de transacções de uma base de dados SQL Server 2005

In SQL Server 2005, a shrink operation (DBCC SHRINKFILE) tries to shrink the specified transaction log file to the requested size immediately. To shrink the transaction log file manually under the full recovery model, first back up the transaction log file. Then, use the DBCC SHRINKFILE statement to shrink the transaction log file.

Typically, shrinking the transaction log file in SQL Server 2005 is faster than shrinking the transaction log file in SQL Server 2000. The reason is that the SQL Server 2005 log manager creates or reuses inactive virtual log files by following the physical disk storage order. Therefore, the inactive part of the transaction log file is usually at the end of the file.

For example, the transaction log file may have 100 virtual log files, and only 2 virtual log files are used. SQL Server 2000 may store the first used virtual log file at the start of the transaction log file and the second used virtual log file in the middle of the transaction log file. To shrink the transaction log file to only 2 virtual log files, SQL Server fills the remaining part of the second virtual log file by using dummy log entries. SQL Server moves the start of the logical log to the next available virtual log file that is specified by the log manager. The log manager may create a virtual log file in the middle of the transaction log file just ahead of the last active virtual log file. In that case, you have to use multiple log backup operations and multiple shrink operations to successfully shrink the transaction log file to 2 virtual log files. In the worst case of this example, you may have to use 50 log backup operations and 50 shrink operations to successfully shrink the transaction log file to 2 virtual log files.

However, in SQL Server 2005, you can perform one DBCC SHRINKFILE statement to shrink the transaction log file immediately to 2 virtual log files. You can do this because the SQL Server 2005 log manager creates 2 virtual log files by following the physical disk storage order. Both of these virtual log files are at the start of the transaction log file.

When you try to shrink a transaction log file that has little free space in SQL Server 2005, you may have to perform an additional log backup operation. The additional log backup operation truncates the transaction log file to a smaller size. This log backup operation is in addition to the three steps that you perform to shrink the transaction log file in SQL Server 2000. For more information, see the Microsoft Knowledge Base article that is mentioned in the “Introduction” section. To shrink a transaction log file that has little free space in SQL Server 2005, follow these steps:

1. Back up the transaction log file to make most of the active virtual log files inactive. Therefore, the inactive virtual log files can be removed in a later step. To do this, run a Transact-SQL statement that is similar to the following Transact-SQL statement. BACKUP LOG TO DISK = ‘
Note In this statement, is a placeholder for the name of the database that you are backing up. In this statement, is a placeholder for the full path of the backup file.

For example, run the following Transact-SQL statement. BACKUP LOG TestDB TO DISK=’C:\TestDB1.bak’
Â
2. Shrink the transaction log file. To do this, run a Transact-SQL statement that is similar to the following Transact-SQL statement. DBCC SHRINKFILE (, ) WITH NO_INFOMSGS
Note In this statement, is a placeholder for the name of the transaction log file. In this statement, is a placeholder for the target size that you want the transaction log file to be. The target size must be reasonable. For example, you cannot shrink the transaction log file to a size that is less than 2 virtual log files.

3. If the DBCC SHRINKFILE statement does not shrink the transaction log file to the target size, run the BACKUP LOG statement that is mentioned in step 1 to make more of the virtual log files inactive.

4. Run the DBCC SHRINKFILE statement that is mentioned in step 2. After this operation, the transaction log file should be similar to the target size.
In summary, the log manager’s algorithm for picking up the next virtual log file changed in SQL Server 2005. Therefore, shrinking the transaction log file in SQL Server 2005 may differ from shrinking the transaction log file in SQL Server 2000:

  • If a log file has lots of free space, shrinking the transaction log file in SQL Server 2005 is faster than shrinking the transaction log file in SQL Server 2000.
  • If a log file has no free space, shrinking the transaction log file in SQL Server 2005 is the same as shrinking the transaction log file in SQL Server 2000.
  • If a log file has little free space, you may have to perform an additional log backup operation in SQL Server 2005 than you have to perform in SQL Server 2000.

REFERENCES
For more information, see the following topics in SQL Server 2005 Books Online:• Shrinking the transaction log
• DBCC SHRINKFILE (Transact-SQL)
• Truncating the transaction log

 Source: http://support.microsoft.com/kb/907511/en-us

SQL Server Uncategorized

Mudar o ownership de um objecto

sp_changeobjectowner

Fonte: http://msdn2.microsoft.com/en-us/library/Aa259618(SQL.80).aspx

read more »

SQL Server

SUBSTRING (Transact-SQL)

Sintax: SUBSTRING ( expressão , início , fim )

Exemplo: Select SUBSTRING(“expressao”, 1, 5) = “expre”

read more »

SQL Server

Examples of how to Calculate Different SQL Server Dates

First Day of Month
select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
Monday of the Current Week
select DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

set DATEFIRST 1

select DATEADD(dd, 1 – DATEPART(dw, getdate()), getdate())

First Day of the Year
select DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
First Day of the Quarter
select DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)
Midnight for the Current Day
Select DATEADD(dd, DATEDIFF(dd,0,getdate()), 0)
Last Day of Prior Month
select dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()Â ), 0))
Last Day of Prior Year
select dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()Â ), 0))
Last Day of Current Month
select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate()Â )+1, 0))
Last Day of Current Year
Select dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()Â )+1, 0))
First Monday of the Month
select DATEADD(wk, DATEDIFF(wk,0,
           dateadd(dd,6-datepart(day,getdate()),getdate())
                              ), 0)    Â

Â

Â

SQL Server

Somando Valores NULL

Select SUM(IsNull(Null,0) + IsNull(NULL,0)) AS valor     -> 0

Select SUM(IsNull(Null,0)) AS valor   -> 0

Select SUM(IsNull(Null,6)) AS valor   -> 6