Archive

Archive for the ‘T-SQL’ Category

Rank function in transact SQL

February 8th, 2012 admin No comments

Rank() function is used to give ranking to the records chosen through a select clause.  Rank function is very commonly used in the industry for many purposes.

The general syntax of rank function is

RANK ( )  OVER ( [  partition by < column_list > ]  order by  <column_list> )

The PARTITION BY clause divides the result set produced by the FROM clause into separate partitions. Rank is applied to each of these partion.

The ORDER BY  clause determines the order in which the RANK values are applied to the records in a partition.

Read more…

Creating databases in SQL Server

January 29th, 2012 admin No comments

 In SQL server, creating a database is as simple as counting 1..2…3…

All you need to do is

  1. open SQL server management studio
  2. Expand your server node.
  3. Right click on databases and choose the option new databases.
  4.  

  5. In general tab – Specify the name of the database and the path of data and log files
  6. Read more…

Query to track index fragmentation in a database

June 30th, 2011 admin No comments

Query to track all the indexes with fragmentation in a database.

 

SELECT 

OBJECT_NAME(object_id) AS TablelName

,(SELECT name FROM sys.indexes WHERE object_id = a.object_id and index_id = a.index_id) IndexName

,avg_fragmentation_in_percent

FROM sys.dm_db_index_physical_stats(DB_ID(‘<<DatabaseName>>’), NULL, NULL, NULL, NULL) a

WHERE avg_fragmentation_in_percent > 40

AND index_type_desc IN(‘CLUSTERED INDEX’, ‘NONCLUSTERED INDEX’)

ORDER BY avg_fragmentation_in_percent DESC

 

The <<DatabaseName>> needs to be filled with the database of your choice.

 

Compound Operators in SQL Server

June 30th, 2011 admin No comments

There was a time when we all wished SQL Server supports compound operators just like any other programming languages. Wouldn’t it be nice to have a shorter syntax for assigning the result of an arithmetic operator?  Well, SQL server 2008 introduced Compound operators that allow you to perform several arithmetic operations using an operand along with equal to (=) operand.

 For example:

Declare @var1  int

Set @var1 = 150

Set @var1 += 100

Read more…

What are SQL Query Hints?

May 11th, 2011 admin No comments

SQL server usually selects the best query plan required to execute a T-SQL query. However, there might be cases where the plans selected are not the best. In such situations, you can use the query hints to suggest the best possible plan/method of executing a query. The Query hints can be applied on all operators in a query. These hints apply to SELECT, DELETE, INSERT, UPDATE and MERGE. You can use the Query hints in the OPTION clause after the query.

Few commonly used Query hints with examples are as below.

Read more…

Understanding MERGE Transact SQL Statement

May 6th, 2011 admin No comments

 By using “Merge”, you can perform insert, delete and update on a table in a single SQL statement. This helps in synchronizing the tables as well.

However while using merge there are several points that you need to keep in mind. Few

  • In a “Merge” statement, a “When Matched” clause with a search condition cannot appear after a ‘When Matched’ clause with no search condition.
  • A “Merge” statement must be terminated by a semi-colon (;).
  • An action of type ‘DELETE’ is not allowed in the ‘WHEN NOT MATCHED’ clause of a MERGE statement.
  • At least one of the three MATCHED clauses must be specified, but they can be specified in any order. A variable cannot be updated more than once in the same MATCHED clause.
  • Any insert, update, or delete actions specified on the target table by the MERGE statement are limited by any constraints defined on it, including any cascading referential integrity constraints.

Few examples of merge are as given below.

Read more…

Advantages and differences between CHAR and VARCHAR datatypes in SQL Server

April 25th, 2011 admin No comments

 

Everyone reading this must have come across these datatypes, but have you ever thought what are the differences and advantages between these two?

The obvious difference that comes to our mind is related to the length. Yes! You are right. The varchar supports variable length and Char supports fixed length. This is the main advantage varchar datatype. for example,  let us consider varchar(10) and char(10) . To store “GEEKEPISODE”, both the datatypes will use the complete length allocated and to store “GEEK”, CHAR datatype will use the complete 10 characters  allocated, but VARCHAR will use only 4.

From the above examples it might seem that VARCHAR is better than CHAR all the time. But remember, CHAR was included as a separate datatype because it has certain advantages over VARCHAR.

VARCHAR uses additional space to store the length of the string stored in it and to mark the end of the string. Whereas, CHAR datatype doesn’t use this additional space.  This certainly is the advantage of CHAR datatype.

Summary:

Read more…

Executing the script in batch file using “sqlcmd” command

March 24th, 2011 admin No comments

I often create batch files to execute sql scripts ( specially SPs) and then schedule it using SQL agent job/Task Scheduler. In this post , I will show you how to create a batch file with sql commands.

First of all, The command that is used to execute SQL queries from commnd prompt is “SQLCMD“. The general syntax of this command is available in the link. I will go with a simple one as below

sqlcmd –E –S Servername –Q Query -o “Output Path”

here
-E = Trusted connection (windows authentication)
-S = Server Name
-Q = CommandLineQuery
-o = Output file path
a simple command on the commnad prompt can be
C:\Users\geekEpisodes>  sqlcmd -E -S “Local-SRV01″ -Q “Select top 10 * from MyTestDatabase..[ForecastHistory]” -o “C:\New Folder\Output.txt”

All the commands that you execute in the command prompt can be executed from batch/command files. to create a batch file with SQL commands follow the steps below

Read more…

Understanding RAISERROR statement in SQL server

November 18th, 2010 admin No comments

RAISERROR statement is used to return error messages to the business applications that executes SQL statements. The usual errors returned by the SQL server may not make much sense to the business applications users hence we overwrite it by using RAISERROR to display meaningful messages. The statement uses same format as a system error or warning messages generated by SQL server.

You can return a user-defined error message by using RAISERROR.  The general syntax is as below

RAISERROR ( { msg_id | msg_str | @local_variable }

    { ,severity ,state }

    [ ,argument [ ,...n ] ] )

    [ WITH option [ ,...n ] ]

 

ExamplesRAISERROR (‘Error raised in TRY block.’, — Message text.

Read more…

Using TRY…..CATCH Construct to handle errors in SQL server

November 16th, 2010 admin No comments

A TRY ….CATCH construct includes a TRY block followed by a CATCH block. The TRY block contains a set of transact SQL statements. If an error occurs in any statements of the TRY block, the control is passed to the CATCH block, which contains another set of SQL statements.

The CATCH block contains SQL statements that executes only during errors in TRY block. The general syntax of the TRY…CATCH block is as shown below

BEGIN TRY

                <SQL Statements…..>

                <SQL Statements…..>

END TRY

BEGIN CATCH

                <SQL Statements…..>

                <SQL Statements…..>

END CATCH

  Read more…