<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-495177919198719500</atom:id><lastBuildDate>Thu, 06 Nov 2025 11:12:36 +0000</lastBuildDate><category>Transact SQL T-SQL</category><category>SQL Server Administration</category><category>SQL Server General</category><category>SQL Server 2012</category><category>Reporting Services SSRS</category><category>SQL Server Training</category><category>SQL Azure</category><category>MySQL</category><category>SQL Server 2014</category><category>Link List</category><category>SQL Data Services</category><category>Analysis Services SSAS</category><category>Integration Services SSIS</category><category>Business Intelligence</category><category>SQL Server Denali</category><title>Microsoft Sql Server Tutorials</title><description>Learn how to use SQL Server 2005 and SQL Server 2008 R2 with free SQL Server tutorials.</description><link>http://www.sqlservercurry.com/</link><managingEditor>noreply@blogger.com (Suprotim Agarwal)</managingEditor><generator>Blogger</generator><openSearch:totalResults>707</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1771900246637980668</guid><pubDate>Thu, 24 Jan 2019 11:36:00 +0000</pubDate><atom:updated>2019-02-07T20:06:19.395-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MySQL</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>GroupBy Clause - SQL Server vs MySQL</title><description>A GROUP BY Clause is used to group the data based on specific columns along with summary information. However there are some differences in usage of this clause in SQL Server and MySQL&lt;br /&gt;
&lt;br /&gt;
Let us create this testing table with some sample data&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;; font-size: small;&quot;&gt;create table testing     &lt;br /&gt;(      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sales_id int,      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; product_id char(7),      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sales_date datetime,      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sales_amount decimal(12,2)      &lt;br /&gt;)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;; font-size: small;&quot;&gt;insert into testing(sales_id,product_id,sales_date,sales_amount)     &lt;br /&gt;select 1,&#39;PR00001&#39;,&#39;2001-01-01&#39;,1200.00 union all      &lt;br /&gt;select 2,&#39;PR00002&#39;,&#39;2003-01-21&#39;,3000.50 union all      &lt;br /&gt;select 3,&#39;PR00002&#39;,&#39;2003-01-21&#39;,2500.00 union all      &lt;br /&gt;select 4,&#39;PR00001&#39;,&#39;2002-02-15&#39;,1000.00 union all      &lt;br /&gt;select 5,&#39;PR00003&#39;,&#39;2005-12-19&#39;,3000.50 union all      &lt;br /&gt;select 6,&#39;PR00003&#39;,&#39;2006-11-01&#39;,8000.00 union all      &lt;br /&gt;select 7,&#39;PR00004&#39;,&#39;2007-04-22&#39;,350.00 union all      &lt;br /&gt;select 8,&#39;PR00004&#39;,&#39;2007-04-22&#39;,590.00 union all      &lt;br /&gt;select 9,&#39;PR00004&#39;,&#39;2007-04-22&#39;,590.00 union all      &lt;br /&gt;select 10,&#39;PR00001&#39;,&#39;2008-05-27&#39;,4800.50&lt;/span&gt; &lt;br /&gt;
&lt;br /&gt;
If you want to get total sales amount for each product, you can write this query both in SQL Server and MySQL&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;; font-size: small;&quot;&gt;select product_id,sum(sales_amount) as sales_amount from testing     &lt;br /&gt;group by product_id&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
As per ANSI SQL, all columns that are not part of aggregate functions should be included in GROUP BY clause&lt;br /&gt;
&lt;br /&gt;
If you run the following code in SQL Server&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;; font-size: small;&quot;&gt;select product_id,sum(sales_amount) as sales_amount from testing&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
You will get an error&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: red;&quot;&gt;Msg 8120, Level 16, State 1, Line 1     &lt;br /&gt;Column &#39;testing.product_id&#39; is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
However if you run this code in MySQL, you will get the following result&lt;br /&gt;
&lt;br /&gt;
Product_id&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sales_amount   &lt;br /&gt;
-----------&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; --------------    &lt;br /&gt;
PR00001&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 25031.50&lt;br /&gt;
&lt;br /&gt;
Because MySQL does the auto grouping for the columns specified in the SELECT statement, if they are omitted in GROUP BY clause, it just simply displays the first value of columns along with total of summary column. In this case, it displays the first product id and total of all products&lt;br /&gt;
&lt;br /&gt;
The following is also possible in MySQL&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;; font-size: small;&quot;&gt;select *,sum(sales_amount) as sales_amount from testing&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
As explained, it will list out all columns of first row along with total of sales_amount. You need to aware of this feature in MySQL while using GROUP BY Clause</description><link>http://www.sqlservercurry.com/2012/09/groupby-clause-sql-server-vs-mysql.html</link><author>noreply@blogger.com (Madhivanan)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-8482308519208549319</guid><pubDate>Wed, 16 Jan 2019 18:40:00 +0000</pubDate><atom:updated>2019-02-07T20:06:45.839-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Inner Join - Concepts and Best practices</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In a database such as SQL Server, we create tables which are related to each other through a common column. For example, if we have to store customers’ related information, then the customer’s personal information gets stored in one table and the same customer’s transaction information, gets stored in another table. Both the tables have &lt;strong&gt;CustID&lt;/strong&gt; as a common column.&lt;br /&gt;
&lt;br /&gt;
We can implement RDBMS (Relational Database Management System) concepts through any database, such as SQL Server. So the same entity’s information flows down in different tables. This is part of the Normalization process within RDBMS framework. &lt;br /&gt;
&lt;br /&gt;
However as part of the requirement, we may need to show a report containing customer information from multiple tables, on a matching column condition. Here arises the need of using the technique of&lt;strong&gt; Joins in SQL&lt;/strong&gt; scripting. &lt;br /&gt;
&lt;br /&gt;
Example - Let us create an Employee specific set of 2 tables in a new database.&lt;br /&gt;
&lt;br /&gt;
Execute the following script in your instance of SQL Server.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Use Master
go
Create Database Inner_Join
go
Use Inner_Join
go
CREATE TABLE EMP
       (EMPNO Integer,
        ENAME Varchar(15),
        JOB Varchar(9),
        MGR Integer,
        HIREDATE datetime,
        SAL Integer,
        COMM Integer,
        DEPTNO Integer)
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;INSERT INTO EMP VALUES
        (7369, &#39;SMITH&#39;, &#39;CLERK&#39;, 7902, &#39;12/17/80&#39;, 800, NULL, 20)
INSERT INTO EMP VALUES
        (7499, &#39;ALLEN&#39;, &#39;SALESMAN&#39;, 7698, &#39;5/20/81&#39;, 1600, 300, 30)
INSERT INTO EMP VALUES
        (7521, &#39;WARD&#39;, &#39;SALESMAN&#39;, 7698, &#39;5/22/81&#39;, 1250, 500, 30)
INSERT INTO EMP VALUES
        (7566, &#39;JONES&#39;, &#39;MANAGER&#39;,   7839, &#39;4/2/81&#39;, 2975, NULL, 20)
INSERT INTO EMP VALUES
        (7654, &#39;MARTIN&#39;, &#39;SALESMAN&#39;, 7698, &#39;9/28/81&#39;, 1250, 1400, 30)
INSERT INTO EMP VALUES
        (7698, &#39;BLAKE&#39;, &#39;MANAGER&#39;,   7839, &#39;5/1/81&#39;, 2850, NULL, 30)
INSERT INTO EMP VALUES
        (7782, &#39;CLARK&#39;, &#39;MANAGER&#39;,   7839, &#39;6/9/81&#39;, 2450, NULL, 10)
INSERT INTO EMP VALUES
        (7788, &#39;SCOTT&#39;,  &#39;ANALYST&#39;,  7566, &#39;12/9/82&#39;, 3000, NULL, 20)
INSERT INTO EMP VALUES
        (7839, &#39;KING&#39;,   &#39;PRESIDENT&#39;, NULL, &#39;11/17/81&#39;, 5000, NULL, 10)
INSERT INTO EMP VALUES
        (7844, &#39;TURNER&#39;, &#39;SALESMAN&#39;, 7698, &#39;9/8/1981&#39;,1500,    0, 30)
INSERT INTO EMP VALUES
        (7876, &#39;ADAMS&#39;, &#39;CLERK&#39;, 7788, &#39;1/12/83&#39;, 1100, NULL, 20)
INSERT INTO EMP VALUES
        (7900, &#39;JAMES&#39;, &#39;CLERK&#39;, 7698,  &#39;12/3/81&#39;, 950, NULL, 30)
INSERT INTO EMP VALUES
        (7902, &#39;FORD&#39;,   &#39;ANALYST&#39;, 7566, &#39;12/3/81&#39;, 3000, NULL, 20)
INSERT INTO EMP VALUES
        (7934, &#39;MILLER&#39;, &#39;CLERK&#39;,  7782, &#39;1/23/82&#39;, 1300, NULL, 10)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;go
CREATE TABLE DEPT
       (DEPTNO INTEGER,
        DNAME VARCHAR(14),
        LOC VARCHAR(13) )
go
INSERT INTO DEPT VALUES (10,&#39;ACCOUNTING&#39;,&#39;NEW YORK&#39;)
INSERT INTO DEPT VALUES (20,&#39;RESEARCH&#39;,&#39;DALLAS&#39;)
INSERT INTO DEPT VALUES (30,&#39;SALES&#39;,&#39;CHICAGO&#39;)
INSERT INTO DEPT VALUES (40,&#39;OPERATIONS&#39;,&#39;BOSTON&#39;)
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Let us see the tables to understand the relationship.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;use Inner_Join
go
select * from dept
go
select * from emp
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;dept-no&quot; border=&quot;0&quot; height=&quot;268&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik5hNqPB8u3OvC2tqwzwJ52Of9JYTDZs_dwS6xHNcQZqhiD1p88eqWpYUSVGsVIoBhks6JV85jx6m-vxd0JoVYzkmOcUpd3sdscCUVij_YZdl_Yvoy9DHqaQkRsbd8mAWFyHQlFnqIg4DG/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;dept-no&quot; width=&quot;400&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
You can observe that Deptno is the common field in both the tables, Dept &amp;amp; Emp. Department details are in Dept table and Employee table contains a DEPTNO column which represents the Department Number an Employee belongs to. Let us see two records of Emp table to get a clarity. Consider the record of SMITH in Emp table. Smith’s Deptno is 20, which means Smith’s Department Name (DNAME) is RESEARCH. Similarly consider ALLEN’s record. His Deptno is 30, which means Allen’s DNAME is Sales. So for the first two records, we have mapped the common column Deptno!&lt;br /&gt;
Now we want to display the ENAME and DNAME for the matching Deptno. This is possible by a technique within SQL scripting that is called as Joins.&lt;br /&gt;
&lt;br /&gt;
There are multiple types of joins, but in this article we are going to focus on Inner Join or also known as Equi-Join. &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Editorial Note:&lt;/strong&gt; Check this artilce to understand &lt;a href=&quot;http://www.sqlservercurry.com/2015/04/types-of-join-in-sql-server-inner-self_26.html&quot;&gt;Types of JOIN in SQL Server - Inner, Self, Outer and Cross JOIN&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;So what is Inner Join?&lt;/strong&gt; Inner join is displaying data from multiple tables on matching values of common field (s), within the associated tables.&lt;br /&gt;
&lt;h3&gt;
Inner Join Syntax&lt;/h3&gt;
There are two types of syntaxes for Inner join:&lt;br /&gt;
&lt;br /&gt;
1) Non-ANSI&lt;br /&gt;
2) ANSI&lt;br /&gt;
&lt;br /&gt;
Let us see the Non-ANSI syntax first:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, dname
from emp, dept
where emp.deptno = dept.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;non-ansi-sql&quot; border=&quot;0&quot; height=&quot;340&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2FgfA1HEdpzi6lazksbVgtt-gIYo0OXmZ2OF0jiCJJSSWXFGTzCRno3OSua8UFn-8LH1isSu6gfO9-M8yBEFXEubyhNFVK9RR1v7szwMcm7wjKFBoJgJXIV6RzVwZ8BTbrq3OtAPNe21j/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;non-ansi-sql&quot; width=&quot;244&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
One thing to note is that in the&lt;i&gt; from&lt;/i&gt; clause of SQL statement, we have two tables separated by a &lt;em&gt;comma&lt;/em&gt;. The mapping of common column is done in the &lt;em&gt;where&lt;/em&gt; clause.&lt;br /&gt;
&lt;br /&gt;
How does it work internally? Whenever a JOIN command is given, then each record of the first table is evaluated with each record of the second table. That means a &lt;u&gt;Cartesian product&lt;/u&gt; happens and then as per the matching values of &lt;em&gt;where&lt;/em&gt; clause, those records are shown. As per the Emp and Dept tables, 14 records of Emp are cross evaluated with 4 records of Dept table. So overall 14 * 4 = 56 evaluations will happen and matching value records are shown.&lt;br /&gt;
&lt;br /&gt;
Now, let us remove the &lt;em&gt;where&lt;/em&gt; clause and see what happens.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, dname
from emp, dept&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;where-clause&quot; border=&quot;0&quot; height=&quot;467&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3nNWRjZHMgoBLq3mGpt6Q5yYwsL4-yBx7I9XqfRi2MR1ktLy74apVqBDalxbDMon_b221z1e20VEeNO3BeK9Zcj8zPHtRqAutRIkWbYmoEFxAjD3fqJwm2KkLRM2fTJ1xTAwQxVFOM1ol/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;where-clause&quot; width=&quot;248&quot; /&gt;&lt;br /&gt;
&lt;img alt=&quot;rows-affected&quot; border=&quot;0&quot; height=&quot;156&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidjM0AfWflXpea-10rRxFruDBqYj0xxWsv0DYXrHBFYMQCAtgZryhJx27FwwcNk_Kmldnp6v4_rOUHg4AgSXnoKEiHH3e2b-UdZRJb6N4uD2B3Y_8k-T1nfXQiyYinMhfBfgDMHWGzhOsr/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;rows-affected&quot; width=&quot;306&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Oops!! The Cartesian product result is displayed now! Due to the absence of &lt;em&gt;where&lt;/em&gt; clause, each evaluation has been displayed as well. So this output is logically going wrong! Actually we have accidentally landed in another type of join that is &lt;strong&gt;Cross Join&lt;/strong&gt;. &lt;br /&gt;
&lt;br /&gt;
Now, let us have the common field for display purpose. We will include the Deptno column along with Ename and Dname columns in the column list.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, dname, deptno
from emp, dept
where emp.deptno = dept.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
It has thrown the following error –&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;ambiguous-column&quot; border=&quot;0&quot; height=&quot;90&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2bztdXiOsDK1D_Cl69LJ4u6GYUoRqeLg7F7NpqBCXMqSPUX6x_QjjogO9a7eQb51vDd9YI54ZAdMpTyvruipG922wD2eSlLD2ZT9F8KzueXe-Q0gfupudZ1eO-uRiD-ZgSBT5GVFbJ7uK/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;ambiguous-column&quot; width=&quot;409&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
The common field’s name is same in both the tables. So a confusion arose in understanding that deptno from which table should be considered. The error would not have come if the common column had different name. In such a case where name is same, it is mandatory to mention the table name&lt;b&gt; &lt;/b&gt;and &lt;b&gt;.&lt;/b&gt; (dot) separator as prefix .&lt;br /&gt;
&lt;br /&gt;
Let us rectify the above query.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, dname, emp.deptno
from emp, dept
where emp.deptno = dept.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;inner-join-result&quot; border=&quot;0&quot; height=&quot;366&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCb0rRPOPjmqsfGjzt-TmkmpoSy-U1xnDdBdzj6-cqq5CmrMEDspv6s_EUMeEJmQo7HYMlzyCFkGovQyeSSa6UocNz3Bv_D8NvZ2HxZcTPYG4iThF3zrrqTBtDZoYYOWgEaNCNxIC27I9o/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;inner-join-result&quot; width=&quot;318&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Ideally table name prefix should be mentioned for each column irrespective of whether it is common or uncommon. Advantage of this approach is that it will give clarity to any other user who is not habitual with the tables &amp;amp; its columns.&lt;br /&gt;
&lt;br /&gt;
So the same query will be written as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select emp.ename, dept.dname, emp.deptno
from emp, dept
where emp.deptno = dept.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
But in projects, table names many a times are lengthy. So mentioning a lengthy table name repeatedly the will be cumbersome. To avoid that, introduce a table alias in the &lt;em&gt;from&lt;/em&gt; clause. Use that alias in the column list and &lt;em&gt;where&lt;/em&gt; clause.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;JOIN – Best practice&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
So now I am coming to the best practice of writing a JOIN statement.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select e.ename, d.dname, e.deptno
from emp e, dept d
where e.deptno = d.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Internally, &lt;em&gt;from&lt;/em&gt; clause is getting executed first, then the &lt;em&gt;where&lt;/em&gt; clause and finally the &lt;em&gt;select&lt;/em&gt; clause as per the above statement. &lt;br /&gt;
&lt;h3&gt;
INNER JOIN – ANSI Syntax&lt;/h3&gt;
So far we have seen the NON-ANSI syntax of joining tables. Now let us see the ANSI syntax. As per ANSI Joins, there are two changes: &lt;br /&gt;
&lt;br /&gt;
1. The comma within &lt;em&gt;from&lt;/em&gt; clause gets replaced by Join type specification &lt;br /&gt;
2. The JOIN condition has to be given using ON clause instead of &lt;em&gt;where&lt;/em&gt; clause. &lt;br /&gt;
&lt;br /&gt;
The select statement will look like this: &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select e.ename, d.dname, e.deptno
from emp e Inner Join dept d
On e.deptno = d.deptno&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Amongst the multiple types of joins, the default type of join is an Inner Join. So &lt;em&gt;Inner&lt;/em&gt; is an optional keyword. The query can have only Join as the keyword which will be as follows: &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select e.ename, d.dname, e.deptno
from emp e Join dept d
On e.deptno = d.deptno &lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
In Non-ANSI style of join, we have observed that if the &lt;em&gt;where&lt;/em&gt; clause is skipped, then it shows a Cartesian product output. On the same lines, let us try to omit the &lt;em&gt;On&lt;/em&gt; clause in ANSI and let’s see what happens.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select e.ename, d.dname, e.deptno
from emp e Join dept d&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
It is throwing an error.&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;incorrect-syntax&quot; border=&quot;0&quot; height=&quot;159&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqMehP4LZgqEBdzrIx8Yfx-9tXIEk3oEn2DIX8bnmRQ2liNOMaXejDOP1bcaYUc6c7imM1HKO3vnsMu6H0Ww7z4qCibkwmfaoPbudsqcES4oSpPDfBtq2hpKB7TdV5R-hUtP0I1wj_wonH/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;incorrect-syntax&quot; width=&quot;452&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
It means that &lt;strong&gt;&lt;i&gt;On&lt;/i&gt; clause is mandatory in ANSI type of join&lt;/strong&gt;. The advantage of ANSI join is that it is a dedicated inner join and it prevents an accidental Cartesian product.&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;About one-to-many relationship for Inner join&lt;/b&gt;&lt;/h3&gt;
The inner or equi join will be logically correct if we have one-to-many relationship between the values of common field. In the Emp and Dept tables, there is such relationship, so the output is correct, i.e a matching deptno is once in the dept table and it is multiple times in the emp table.&lt;br /&gt;
&lt;br /&gt;
What if there is a many-to-many relationship within the tables? Right now the deptno column is not having a primary constraint in the Dept table. So we can add one more record of the same deptno 10.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Dept Values(10, &#39;Testing&#39;, &#39;CALIFORNIA&#39;)
Go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
So right now there are 2 records of the same deptno 10 in dept table.&lt;br /&gt;
&lt;br /&gt;
Let us see that –&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from dept&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;duplicate-records&quot; border=&quot;0&quot; height=&quot;184&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQwACRj4pVQW0sHt4RgnkHzIxJ3IpNWjyDHXggtZdV101myxb5xn95csxPdUn5juwORR3DoGd8awl5xDAIYYBJ4JvZiHnluQCrlpdR2u1DO1OWTeaieUs59-rxL4XU7RomOg7lpW0_xn0X/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;duplicate-records&quot; width=&quot;363&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Now we will execute the same ANSI join statement again.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select e.ename, d.dname, e.deptno
from emp e Join dept d
On e.deptno = d.deptno &lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
The output has logically gone wrong!&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;wrong-output&quot; border=&quot;0&quot; height=&quot;450&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvt-oJb5M7YqmaVTOc_89tEA7kdP5QQZfvXJBnCFmxOWPbZeU9UEWqyF-03fXIu_Bnp4OadNZwkfErz64LINUosSNe-xyaaCcNb0xXL_FDsT9o6jrzBVokWCtTuHq0Gb6MeUw16EmSTJVr/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;wrong-output&quot; width=&quot;336&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
CLARK, KING and MILLER are displayed in both Accounting &amp;amp; Testing departments.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;An Inner join will give correct result only when there is one-to-many relationship&lt;/strong&gt;. Therefore normally this problem gets eliminated when we have Primary Key and Foreign Key relationship within the common field.&lt;br /&gt;
&lt;br /&gt;
Let us delete this additional record of deptno 10 so that everything goes back to normal.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Delete from Dept
where DName = &#39;Testing&#39;
go&lt;/pre&gt;
&lt;h3&gt;
Important features of Inner Join&lt;/h3&gt;
1. Common field name may be same or different.&lt;br /&gt;
2. The data type and size of common fields should be ideally the same.&lt;br /&gt;
3. If the data type is not same, then using type casting functions the data types should be made same in the On clause.&lt;br /&gt;
4. There should be one-to-many relationship within the common field values.&lt;br /&gt;
I hope through this article, your Inner Join principle now is as sound as a dollar!&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/03/sql-server-inner-join-concepts-best.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik5hNqPB8u3OvC2tqwzwJ52Of9JYTDZs_dwS6xHNcQZqhiD1p88eqWpYUSVGsVIoBhks6JV85jx6m-vxd0JoVYzkmOcUpd3sdscCUVij_YZdl_Yvoy9DHqaQkRsbd8mAWFyHQlFnqIg4DG/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1066902544160011817</guid><pubDate>Wed, 19 Dec 2018 10:16:00 +0000</pubDate><atom:updated>2019-02-07T20:07:23.102-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Query Pagination</title><description>&lt;em&gt;This article was authored by Praveen Dabade.&lt;/em&gt;&lt;br /&gt;
&lt;br /&gt;
In SQL Server 2012, Microsoft introduced a couple of T-SQL Enhancements. One of them is Query Pagination which we will explore today.&lt;br /&gt;
&lt;br /&gt;
For this demonstration, I am using the Northwind database to demonstrate this new feature. Now in most of the applications, a common requirement is how to fetch the data from the database servers, page wise. &lt;br /&gt;
&lt;br /&gt;
In earlier versions of SQL Server like SQL Server 2005/2008/R2, we can implement Pagination by using different techniques. For example, we implement pagination using ROW_NUMBER() function or CTE - Common Table Expression.&lt;br /&gt;
&lt;br /&gt;
In SQL Server 2012, Microsoft has introduced Pagination as a part of Select query in a Order By clause. Now you will have to use OFFSET and FETCH NEXT with the order by clause. &lt;br /&gt;
&lt;br /&gt;
Let&#39;s take a look at a few examples. I am using Northwind database for this demonstration. I have created a Stored Procedure which takes two parameters. First parameter takes the page number and the second parameter ask you to fetch the no. of records for that page. The stored procedure code is as below - &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;query-pagination&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieP0Ebg6byUMKRzMoMfFav-pJ0LTL5o6kCTsoZd_qyC3KXu5prQnzKeIUIAfWh0-gZ4-buDZkLAcjqghsqzQUQhBv_uNglWm8E08cEPVarb5wEJi02bKsbC4s1kRVJgvZwsIDZ3zXoE8lt/?imgmax=800&quot; height=&quot;161&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;query-pagination&quot; width=&quot;597&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
If you execute the above stored procedure &lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;; font-size: small;&quot;&gt;EXEC FetchPagedRecords 2,10&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
you will get the following results -&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;image&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigkIK8hXaw35pSwYvCgOWXHScVAMCcI72KqNOkKQXGnb5BZQHRNj_Kdx6YKA_pS34jDGyaxDO2pII2uj9tHEfuThCsI6xSmrkGOMOYIPP23p8Kwu4-MfqsKvsJYimshyphenhyphen40D8b5bdB_ZQpE/?imgmax=800&quot; height=&quot;242&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; margin: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;395&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
The OFFSET specifies the number of rows to skip before it starts returning the rows and FETCH NEXT specifies the number of rows to be returned.&lt;br /&gt;
&lt;br /&gt;
Microsoft has introduced an easy way of implementing Data Paging in SQL Server 2012 by adding OFFSET and FETCH NEXT in an Order By clause. I hope you will use it in your applications.</description><link>http://www.sqlservercurry.com/2016/01/sql-server-2012-query-pagination.html</link><author>noreply@blogger.com (Suprotim Agarwal)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieP0Ebg6byUMKRzMoMfFav-pJ0LTL5o6kCTsoZd_qyC3KXu5prQnzKeIUIAfWh0-gZ4-buDZkLAcjqghsqzQUQhBv_uNglWm8E08cEPVarb5wEJi02bKsbC4s1kRVJgvZwsIDZ3zXoE8lt/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-5196726310319717521</guid><pubDate>Wed, 20 Dec 2017 12:05:00 +0000</pubDate><atom:updated>2018-01-11T05:17:40.485-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server Administration</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>Shrink a Live SQL Server Database and Logs - Caveats and Best Practices</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;i&gt;Updated on December 20th, 2017.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
If you have deleted a lot of data in the database and truncated some tables, probably you may want to shrink database files to recover the unused space. Basically shrinking will move the data pages at the end of the file into unoccupied space, available in the front of the file. &lt;br /&gt;
&lt;br /&gt;
You can use the DBCC SHRINKDATABASE command. For example, this command &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;DBCC SHRINKDATABASE (your_database,10) &lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
will decrease database size and allow for 10 percent free space. &lt;br /&gt;
&lt;br /&gt;
You can also shrink log file alone using DBCC SHRINKFILE command Take full back up of the database and run the following : &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;ALTER DATABASE your_database SET RECOVERY SIMPLE; 

DBCC SHRINKFILE (your_database_Log, 10); 

ALTER DATABASE your_database SET RECOVERY FULL; &lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
It will set the log file size to 10 MB &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Caveats of shrinking database and logs:&lt;/strong&gt; &lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
1. SHRINK commands should not be done frequently as it will increase the index fragmentation. &lt;br /&gt;
&lt;br /&gt;
2. It is a fully logged operation which will increase the log size and slows down the performance &lt;br /&gt;
&lt;br /&gt;
3. Shrinking is not possible while the current database is being backed up up or restored &lt;br /&gt;
&lt;br /&gt;
4. Shrinking is not possible when columnstore index is enabled &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Best practices&lt;/strong&gt; &lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
1. Use SHRINK only if a lot of operations such as TRUNCATE and DROP has lead to unused space &lt;br /&gt;
&lt;br /&gt;
2. Take full backup before shrinking database files. If you shrink log file, set the Recovery mode into SIMPLE before shrinking and make it FULL after shrinking &lt;br /&gt;
&lt;br /&gt;
3. Never turn ON AUTO SHRINK option &lt;br /&gt;
&lt;br /&gt;
4. Always rebuild indexes after SHRINKING the database files to avoid fragmentation &lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/03/shrink-live-sql-server-database-and.html</link><author>noreply@blogger.com (Madhivanan)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-7169804981074302661</guid><pubDate>Fri, 01 Dec 2017 13:16:00 +0000</pubDate><atom:updated>2018-01-11T05:18:04.073-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server ISNULL() With Multi Column Names</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Many a times we come across null values within tables in SQL Server. Null values are the values with no data; that means the data is missing or unknown. In this article, initially we will understand the &lt;strong&gt;SQL Server IsNull&lt;/strong&gt; function, then we will move towards extending the IsNull functionality using Coalesce function.&lt;br /&gt;
&lt;br /&gt;
Let us see the following example.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Identification
(empid Integer,
ename varchar(30) NOT NULL,
passport_number char(15) ,
license_number char(15) ,
pan char(15) ,
credit_card_number char(15) ,
account_number char(15) 
)
insert into identification values(1,&#39;John&#39;,null,null,&#39;PN-78654&#39;,&#39;CC-12345&#39;,&#39;AN-3456&#39;)
insert into identification values(2,&#39;Martin&#39;,&#39;PS-566774&#39;,null,null,null,null)
insert into identification values(3,&#39;Smith&#39;,null,null,null,null,null)
insert into identification values(4,&#39;Roger&#39;,null,null,null,null,&#39;AN-9876&#39;)
insert into identification values(5,&#39;King&#39;,null,null,null,&#39;CC-8787&#39;,&#39;AN-9878&#39;)
go
select * from identification
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql1-identification-table&quot; border=&quot;0&quot; height=&quot;137&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_NeYNkuTjCunfwnw5EK039Ner2E0TMt8mW03G9MIv8QYqvNGUneQs22oGmbLQS12jFRhRXsvbTxEjFqCqpOuZG7qK6ZWbl1EE83VtNv21m5IOf-TWsjdcLNOfT3pCDjK-OZhX6v1rEKvM/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql1-identification-table&quot; width=&quot;574&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image1-Identification-Table&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
In the above table, every employee has an identity proof which is either a passport number, license number, pan, credit card or account number.&lt;br /&gt;
&lt;h3&gt;
SQL Server ISNULL() Function Example&lt;/h3&gt;
Syntax: &lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;IsNull(Parameter1, Value if null)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
IsNull function returns the first parameter if it’s not null. If the first parameter is null, then it returns the second parameter.&lt;br /&gt;
&lt;br /&gt;
Suppose we want to see if an employee has a passport or not, here the IsNull function can help us.&lt;br /&gt;
&lt;br /&gt;
See the following example of using SQL Server &lt;strong&gt;ISNULL in a Select Statement&lt;/strong&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select empid, ename, IsNull(Passport_Number, &#39;Not Found&#39;) 
as &#39;Passport Status&#39; from identification&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql2-isnull-with-single-column&quot; border=&quot;0&quot; height=&quot;178&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQCd7OrAQaxsJZwT0QdvLCHmN42LWg7dRGSaa94jSE7G9XshwIgZsfDYFhZoxdnoetG0WlrdwV0kcb65cjesdGUry-KTJwp9KwoBWnHEB1FcaCRcKRsq1v7SIaATzGgMItXD75z42ikknx/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql2-isnull-with-single-column&quot; width=&quot;233&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image2-IsNull-With-Single-Column&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;strong&gt;Limitation of IsNull() function:&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
IsNull function can check only if one value is null. It cannot check null for multiple values. That means it is not capable of handling the functionality of checking if the first parameter is null and then move on to check the next parameter for null.&lt;br /&gt;
&lt;br /&gt;
Now assume that for report generation, we want to get the passport number or license number or pan number etc. for reference purpose. If passport number is null, then we need to extract the license number. If license number is null then pan, if pan is null then account number. If all are null then we need to flag a message ‘Invalid’.&lt;br /&gt;
&lt;br /&gt;
The problem is that IsNull function here needs to be used in a nesting manner.&lt;br /&gt;
&lt;br /&gt;
Let us see the ISNULL being used in a select statement in a nested fashion:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select empid, ename, 
IsNull(Passport_Number,IsNull(License_Number, 
IsNull(PAN, IsNull(Credit_Card_Number, IsNull(Account_Number,&#39;Invalid&#39;))))) 
as &quot;Status&quot;
from identification&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql3-isnull-multiple-columns&quot; border=&quot;0&quot; height=&quot;145&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjU_GI_I53H5mpHzy0IKAepn0qExG73GXffL-Kl12AIODsKVSe2RvL5fjbtsZPozIVU9nNmYrCBCScNQHw_er6cWhYwW9rTXEwrUUr0TIiJET4tnEVGH6pPhrvXrFVVDHY82-zs_YKpuOgb/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql3-isnull-multiple-columns&quot; width=&quot;191&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image3-IsNull-Multiple-Columns&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
In the above select statement, we have used IsNull function 5 times to get the desired output.&lt;br /&gt;
&lt;h3&gt;
ISNULL vs Coalesce Function:&lt;/h3&gt;
There is an alternative way using another SQL Server function known as Coalesce. &lt;br /&gt;
&lt;br /&gt;
Syntax of Coalesce:&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;COALESCE( parameter1, parameter2, parameter3,……. parameter_n , default_parameter)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Coalesce can take multiple parameters. It returns the first not null parameter. If all the parameters are null, then it will return the default parameter.&lt;br /&gt;
&lt;br /&gt;
In other words, we can say that coalesce behaves as per the following syntax as well:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;CASE
   WHEN (parameter1 IS NOT NULL) THEN expression1
   WHEN (parameter2  IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
So instead of nesting IsNull function multiple times, we can use a &lt;u&gt;single&lt;/u&gt; coalesce function and get the same output as shown here:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select empid, ename, 
Coalesce(Passport_Number,License_Number,PAN,Credit_Card_Number,Account_Number,&#39;Invalid&#39;)
as &quot;Using Coalesce&quot; from identification&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql4-coalesce&quot; border=&quot;0&quot; height=&quot;158&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYEzpodL12wY7gTjTSB21TIEvIpqKOaO0vo3xeOfvg4jfzpJRH82RjY4VlnTJ0YtXpeUgm75-AUyQSYarcAlPYN6l1XIS0EDcMq9tk6w2edhUHeV44Wl2klppopNj96eL0TWOU1K0WLKtx/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql4-coalesce&quot; width=&quot;213&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image4-Coalesce&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h4&gt;
Conclusion:&lt;/h4&gt;
We have seen how the SQL Server IsNull function is suitable for checking one null value and how usage of coalesce function can eliminate the need of using IsNull function redundantly.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/06/sql-server-isnull-with-multi-column_18.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_NeYNkuTjCunfwnw5EK039Ner2E0TMt8mW03G9MIv8QYqvNGUneQs22oGmbLQS12jFRhRXsvbTxEjFqCqpOuZG7qK6ZWbl1EE83VtNv21m5IOf-TWsjdcLNOfT3pCDjK-OZhX6v1rEKvM/s72-c?imgmax=800" height="72" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-8884503091734034975</guid><pubDate>Thu, 09 Nov 2017 08:29:00 +0000</pubDate><atom:updated>2018-01-11T05:18:27.515-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server T-SQL DateDiff Example</title><description>How do we find the difference between two dates in SQL Server. Not just the difference in the number of days, but also number of weeks, months.&lt;br /&gt;
&lt;br /&gt;
The answer is by using &lt;strong&gt;DateDiff in SQL Server. &lt;/strong&gt;Datediff is also suitable for getting the time elapsed between the start and end of a process. &lt;br /&gt;
&lt;br /&gt;
Here are some real life examples of how &lt;strong&gt;t-sql datediff&lt;/strong&gt; can be used to get a date difference:&lt;br /&gt;
&lt;br /&gt;
1. Calculating the number of days remaining for a postpaid mobile service before it expires? Here an Automated system can calculate the date difference in sql and send an SMS to a customer informing him/her of the number of days remaining.&lt;br /&gt;
&lt;br /&gt;
2. Particularly suitable in embedded systems to note the time taken for each process while manufacturing a product.&lt;br /&gt;
&lt;br /&gt;
3. In library management automation to keep track of the number of days a book had been issued to a customer.&lt;br /&gt;
&lt;br /&gt;
4. For daily login-logout required in an electronic attendance software system of any company. The tsql datediff function can be used to calculate the exact working hours of every employee.&lt;br /&gt;
&lt;br /&gt;
The signature of this function is as follows:&lt;br /&gt;
&lt;br /&gt;
DATEDIFF( interval, date1, date2 )&lt;br /&gt;
&lt;br /&gt;
where &lt;em&gt;date 1&lt;/em&gt; &amp;amp; &lt;em&gt;date 2&lt;/em&gt; can be the actual date or a part of date like an year.&lt;br /&gt;
&lt;br /&gt;
Note: date1 should be greater than or equal to date2.&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;Interval &lt;/em&gt;here can be any of the following as shown in the following chart:&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;t-sql-date-diff&quot; border=&quot;0&quot; height=&quot;370&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsR-2D6J6cMvLUCvos6YrALkN-HI1Hw4WY8DsyleO9yxybZQcJSQiD8hqk9m4b4kREvDVC2LrGUSeJnGCjWrSlXGXk_15CMfIIYfcsZOy5rp8-6E0xNFxoFWGNKOGn0EIAKPvet45gRhtD/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;t-sql-date-diff&quot; width=&quot;384&quot; /&gt;&lt;br /&gt;
&lt;i&gt;image1-t-sql datediff interval&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Let us see some examples to make it more clear and interesting.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select datediff (yy, &#39;1984&#39;, &#39;1997&#39;)  -- 13 years difference

select datediff (dd, &#39;1984&#39;, &#39;1986&#39;) -- 731 days difference

select datediff (mm, &#39;1984&#39;, &#39;1986&#39;) -- 24 months difference

select datediff (qq, &#39;1984&#39;, &#39;1986&#39;) -- 8 quarters difference

select datediff (hour,&#39;2016/05/02 11:00&#39;, &#39;2016/05/02 14:45&#39; 
-- 3 hours difference&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;h3&gt;
Database Oriented Example&lt;/h3&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
The DateDiff SQL function can also be used in a &lt;em&gt;where&lt;/em&gt; clause.&lt;br /&gt;
&lt;br /&gt;
Let us create a sample database for the same in our SQL Server instance.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Use Master
go
create database DateDiff_Demo
go
Use DateDiff_Demo
go
create table Compaints_Details
(ComplaintID Integer Identity,
 CustId Varchar(7),
 Complaint_Description Varchar(100),
 Engineer_ID Varchar(4),
 Date_of_Complaint date,
 Date_of_Resolve date
 )
 Insert into Compaints_Details 
(CustiD, Complaint_Description, Engineer_ID, 
 Date_of_Complaint,Date_of_Resolve)
 Values
 (&#39;C1&#39;, &#39;Modem problem&#39;, &#39;E1&#39;, &#39;21-Apr-2016&#39;, &#39;24-Apr-2016&#39;)

 Insert into Compaints_Details 
(CustiD, Complaint_Description, Engineer_ID, 
  Date_of_Complaint,Date_of_Resolve)
 Values
 (&#39;C2&#39;, &#39;Wire Connection problem&#39;, &#39;E1&#39;, &#39;22-Apr-2016&#39;, &#39;22-Apr-2016&#39;)

 Insert into Compaints_Details 
 (CustiD, Complaint_Description, Engineer_ID, 
  Date_of_Complaint,Date_of_Resolve)
 Values
 (&#39;C3&#39;, &#39;Socket problem&#39;, &#39;E1&#39;, &#39;23-Apr-2016&#39;, &#39;28-Apr-2016&#39;)

 Insert into Compaints_Details 
 (CustiD, Complaint_Description, Engineer_ID, 
  Date_of_Complaint,Date_of_Resolve)
 Values
 (&#39;C5&#39;, &#39;LAN problem&#39;, &#39;E1&#39;, &#39;29-Apr-2016&#39;, &#39;29-Apr-2016&#39;)
 GO
 select* from Compaints_Details
 go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql datediff sample data&quot; border=&quot;0&quot; height=&quot;122&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCxzNg-d5XVyo45fDvMOk8tEkZT1t5dO1hXkWgaXeTSCwUYWlrZal9VcxezO2x8uen-0vR7fvZ-7f_ELP9jr2NtlgSBqLtS074ufenHM3UB3P2s75Pn717lt_AyPv0nPfHIJ7_o9llcT_e/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql datediff sample data&quot; width=&quot;554&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image2-SampleData to run a sql datediff query&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Let us say we want to see how many days were elapsed for every complaint to get resolved.&lt;br /&gt;
&lt;br /&gt;
Here we will use the Tsql DateDiff function.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT  [ComplaintID]
      ,[CustId]
      ,[Complaint_Description]
      ,[Engineer_ID]
      ,[Date_of_Complaint]
      ,[Date_of_Resolve]
      , DateDiff(dd, [Date_of_Complaint]
      , [Date_of_Resolve]) as [Days taken to resolve]
FROM [DateDiff_Demo].[dbo].[Compaints_Details]&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;tsql datediff days&quot; border=&quot;0&quot; height=&quot;94&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgi6rV0fn6L_hGwfBCWJwZsYtku8RWCiHnaeNjGReA2tYD8lGSq4hwFomwv0l4mY7nixk0xcuPDvUiLbXgDu6yNAi4y0tawBbgfV2VzPFJxOp_2HkMNL_Qy__V1re_jz4LLQuL_TKJyVaMa/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;tsql datediff days&quot; width=&quot;504&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image3-DaysTaken before a complaint was resolved&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h3&gt;
Conclusion:&lt;/h3&gt;
&lt;i&gt;&lt;/i&gt;&lt;br /&gt;
And that’s how we can use the SQL Server T-SQL DateDiff function to calculate the day, month, year, and time part differences between two specified dates.</description><link>http://www.sqlservercurry.com/2016/06/sql-server-t-sql-datediff-example_9.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsR-2D6J6cMvLUCvos6YrALkN-HI1Hw4WY8DsyleO9yxybZQcJSQiD8hqk9m4b4kREvDVC2LrGUSeJnGCjWrSlXGXk_15CMfIIYfcsZOy5rp8-6E0xNFxoFWGNKOGn0EIAKPvet45gRhtD/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-2944690168826994528</guid><pubDate>Thu, 26 Oct 2017 05:52:00 +0000</pubDate><atom:updated>2018-01-11T05:19:21.981-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server: Return Newly Inserted Row</title><description>Whenever you &lt;strong&gt;insert a new row in a SQL Server table&lt;/strong&gt; that contains default values, you may want to &lt;strong&gt;return the newly inserted row&lt;/strong&gt; to the user, along with the default value generated. However while doing a plain INSERT statement, all you get is the total number of rows affected. &lt;br /&gt;
&lt;br /&gt;
Here’s an example:&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;insert-row&quot; border=&quot;0&quot; height=&quot;289&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrz3GlLkVaOZIv9_uN_TOI_OUpnoggoX-SsMjiLvSrsLNLrUJKDbXAynQYPBWTQQAobeO9qnbRpIlDal2pWz0HsuhzDFgMYG5ZLPwqjl2XiZbABYiwRkUTvu5YZACgz21Kcz0VDHICpjK5/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;insert-row&quot; width=&quot;359&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Here we are using the &lt;a href=&quot;http://www.sqlservercurry.com/2007/12/generate-unique-number-in-sql-server.html&quot; title=&quot;Generate Unique Number&quot;&gt;NEWID() to generate a unique customer number&lt;/a&gt; in each row. However as you can see, the user does not get to see the default ID that got generated for the newly inserted rows. In order to get back the row values that were inserted, use the OUTPUT clause of the INSERT statement as shown here:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;INSERT INTO #TT (Name, AreaCode)
OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.AreaCode
SELECT &#39;Suprotim&#39;, 2355 UNION ALL
SELECT &#39;Anush&#39;, 2388&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
and this time you get to see the newly inserted rows:&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;sql-server-output-insert&quot; border=&quot;0&quot; height=&quot;237&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjascaQJuI7fi6qShR07xIsVbtxkYFQLMtuNGOEcB0S4AO8QQQq-gZk8frvacbOkEBGJHn89r3ShAeaDkoVnmsGXz3j_zn7WiKcHxKgPR5YA_7xNf9a-dF6i23VbkioqRqYk3exUh8P6KK7/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-server-output-insert&quot; width=&quot;434&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
As you can see, we have added the OUTPUT clause right after the INSERT statement. The rows inserted into the table are captured in the virtual table INSERTED and returned back as a result set.&lt;br /&gt;
&lt;br /&gt;
In case you are wondering, yes it is possible to capture the result set in a table or &lt;a href=&quot;http://www.sqlservercurry.com/2013/12/temporary-table-variables-in-sql-server.html&quot; title=&quot;Table Variable&quot;&gt;table variable&lt;/a&gt;. Assuming there is a Table variable called @TempTbl, just use the following:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql; highlight: [3];&quot;&gt;INSERT INTO #TT (Name, AreaCode)
OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.AreaCode
INTO @TempTbl
SELECT &#39;Suprotim&#39;, 2355 UNION ALL
SELECT &#39;Anush&#39;, 2388&lt;/pre&gt;
&lt;div class=&quot;brush: sql; highlight: [3];&quot;&gt;
&lt;/div&gt;
and now you can do further processing on this data using @TempTbl. 


</description><link>http://www.sqlservercurry.com/2016/01/sql-server-return-newly-inserted-row.html</link><author>noreply@blogger.com (Suprotim Agarwal)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrz3GlLkVaOZIv9_uN_TOI_OUpnoggoX-SsMjiLvSrsLNLrUJKDbXAynQYPBWTQQAobeO9qnbRpIlDal2pWz0HsuhzDFgMYG5ZLPwqjl2XiZbABYiwRkUTvu5YZACgz21Kcz0VDHICpjK5/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1402468643901498396</guid><pubDate>Sat, 16 Sep 2017 01:08:00 +0000</pubDate><atom:updated>2018-01-11T05:20:13.830-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Azure</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>Calculate SQL Azure Database Size</title><description>I was looking out for a correct way to programmatically determine the size of a SQL Azure database. After searching many solutions, I finally found one shared by &lt;a href=&quot;https://social.msdn.microsoft.com/profile/Dimitri+Furman&quot;&gt;Dimitri Furman&lt;/a&gt; of the SQL Server team. &lt;br /&gt;
&lt;br /&gt;
His solution involves using the &lt;strong&gt;sys.database_files&lt;/strong&gt; dmv and the FILEPROPERTY function with the ‘SpaceUsed’ argument. &lt;br /&gt;
&lt;br /&gt;
To those new to sys.database_files, this system catalog view stores information and properties about each file for a database. Since it is a db-level view, it gives information about files in the current database only. Five properties that could be of interest are: logical filename, physical filename, initial size, maximum size and a growth increment.&lt;br /&gt;
&lt;br /&gt;
To determine how much space is used in a file, you can use FILEPROPERTY with SpaceUsed.&lt;br /&gt;
&lt;br /&gt;
Here’s an example: SELECT FILEPROPERTY(‘SomeFile’, ‘SpaceUsed’); I have often used the FILEPROPERTY function in the past while monitoring the progress of a SHRINK operation.&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Query for calculating Size of a SQL Azure Database&lt;/span&gt;&lt;/h2&gt;
Here’s how to combine sys.database_files with FILEPROPERTY to programmatically calculate the size of a SQL Azure database.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT 
SUM(CAST(FILEPROPERTY(name, &#39;SpaceUsed&#39;) AS bigint) * 8192.) 
AS DatabaseSizeInBytes,
SUM(CAST(FILEPROPERTY(name, &#39;SpaceUsed&#39;) AS bigint) * 8192.)/1024 /1024
AS DatabaseSizeInMB,
SUM(CAST(FILEPROPERTY(name, &#39;SpaceUsed&#39;) AS bigint) * 8192.)/1024/1024/1024 
AS DatabaseSizeInGB
FROM sys.database_files
WHERE type_desc = &#39;ROWS&#39;;&lt;/pre&gt;
&lt;br /&gt;
Let’s understand this query.&lt;br /&gt;
&lt;br /&gt;
FILEPROPERTY() returns an int value for a file name stored within sys.database_files. Since sys.database_files is a db-level view, it gives information about files in the current database only. If a file is not present, null value is returned. &lt;br /&gt;
&lt;br /&gt;
Since SpaceUsed represents &quot;pages&quot; and a page is 8 KB in SQL Server, so multiplying by 8192 gets the total bytes. Then dividing two times by 1024 converts the output to MB, and dividing by three times by 1024 converts the output to GB.&lt;br /&gt;
&lt;br /&gt;
CAST is for casting the value to type bigint&lt;br /&gt;
&lt;br /&gt;
If anybody is wondering about the dot (&lt;code&gt;.) &lt;/code&gt;after an 8192, then it is to convert the result implicitly to a decimal value.&lt;br /&gt;
&lt;br /&gt;
Please note that logs are excluded for the purposes of determining database size.&lt;br /&gt;
&lt;br /&gt;
To know about Azure SQL Database resource limits, check &lt;a href=&quot;https://docs.microsoft.com/en-in/azure/sql-database/sql-database-resource-limits&quot; title=&quot;https://docs.microsoft.com/en-in/azure/sql-database/sql-database-resource-limits&quot;&gt;https://docs.microsoft.com/en-in/azure/sql-database/sql-database-resource-limits&lt;/a&gt;</description><link>http://www.sqlservercurry.com/2016/11/calculate-sql-azure-database-size.html</link><author>noreply@blogger.com (Suprotim Agarwal)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-3681519188865445432</guid><pubDate>Sun, 27 Aug 2017 03:14:00 +0000</pubDate><atom:updated>2018-01-11T05:20:38.139-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>Remove Non-Alphabet Characters from a String–SQL Server</title><description>Suppose you have a string that contains numbers and other special characters and you want to keep only alphabets and remove all the other characters. One way to do this is to use a while loop that parses each character&lt;br /&gt;
&lt;br /&gt;
Here is the code for the same&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;; font-size: small;&quot;&gt;declare @str varchar(20)     &lt;br /&gt;set @str=&#39;ab12#89L(h12k&#39;      &lt;br /&gt;Select @str as &#39;Original String&#39;      &lt;br /&gt;declare @temp_str varchar(20), @i int      &lt;br /&gt;select @temp_str =&#39;&#39;,@i=1      &lt;br /&gt;while @i&amp;lt;=len(@str)      &lt;br /&gt;begin      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set @temp_str=@temp_str+case when substring(@str,@i,1) like &#39;[a-zA-Z]&#39; then substring(@str,@i,1) else &#39;&#39; end      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set @i=@i+1      &lt;br /&gt;end      &lt;br /&gt;select @temp_str as &#39;String with Alphabets&#39;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
The code inside the While loop takes each character and check if it is in the range a-z or A-Z and appends that character with another variable. Other characters will not get appended. So at the end of while loop, the second variable will have only alphabets. &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;image&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRdHw6qMBr3dMd15gsoBxxn7aGplcMxaz_O1rETUV1C5thnMpKOff23RyAyeKTMBxybTKooxH73cC4Xfis5eDiYiP1Vvsu8Zr8j3Z5r4KARfw1cEvpvP8S_GtdgVuJ-vhO_addf1wRz7w/?imgmax=800&quot; height=&quot;233&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;187&quot; /&gt;</description><link>http://www.sqlservercurry.com/2012/12/remove-non-alphabet-characters-from.html</link><author>noreply@blogger.com (Madhivanan)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRdHw6qMBr3dMd15gsoBxxn7aGplcMxaz_O1rETUV1C5thnMpKOff23RyAyeKTMBxybTKooxH73cC4Xfis5eDiYiP1Vvsu8Zr8j3Z5r4KARfw1cEvpvP8S_GtdgVuJ-vhO_addf1wRz7w/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-5235219444158222271</guid><pubDate>Mon, 19 Jun 2017 03:07:00 +0000</pubDate><atom:updated>2018-01-11T05:21:37.740-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>Nested Case Statement in SQL Server</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This article is a continuation of &lt;a href=&quot;http://www.sqlservercurry.com/2016/04/sql-server-case-statement-and-case-when_22.html&quot;&gt;SQL Server CASE Statement and CASE WHEN Examples&lt;/a&gt; . Today we will learn about Nested Case Statement in SQL Server.&lt;br /&gt;
&lt;br /&gt;
We can nest CASE statements similar to nested ifs that we find in most programming languages.&lt;br /&gt;
&lt;br /&gt;
Let us see an example.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job, sal, case  -- Outer Case
    when ename like &#39;A%&#39; then
    case when sal &amp;gt;= 1500 then &#39;A&#39; -- Nested Case
    end
    when ename like &#39;J%&#39; then
    case when sal &amp;gt;= 2900 then &#39;J&#39; -- Nested Case
    end
end as &quot;Name-Grade&quot;            
From Emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;7-nested-case&quot; border=&quot;0&quot; height=&quot;339&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhk44scpKgWj-bFfLpS4waYPuZZ_GBSqt9Rkcy7WZpd4hsGM99P4j5cBK8WUL9SmbAiFPPyzjS3N6gbHBmCXqL5hfusuYAyG8We43X3Vn9D4-BQc_DQ5vufPQaFy-kCXWISLL9RgtQrZAPt/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;7-nested-case&quot; width=&quot;394&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 7-Nested-Case&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Limit of nesting a CASE function is up to &lt;b&gt;10 levels &lt;/b&gt;only.&lt;br /&gt;
&lt;br /&gt;
In the following example, the limit of 10 is completely utilized.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Declare @x int
set @x = 1
Select 
case when @x &amp;lt;= 100 then  -- Level 1
 case when @x &amp;lt;= 90 then -- Level 2
    case when @x &amp;lt;= 80 then -- Level 3
        case when @x &amp;lt;= 70 then -- Level 4
            case when @x &amp;lt;= 60 then -- Level 5
                case when @x &amp;lt;= 50 then -- Level 6
                    case when @x &amp;lt;= 40 then -- Level 7
                       case when @x &amp;lt;= 30 then --Level 8
                         case when @x &amp;lt;= 20 then--Level 9
                           case when @x&amp;lt;= 10 then--Level 10
                                100
End End End End End End End End End 
End as &quot;Nested Case&quot; 
--Ending all levels!&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;8-nested-case-upto-10-levels&quot; border=&quot;0&quot; height=&quot;70&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPoIDOo_vU_eJIQPklosGTZ-eMeTGDlwTKg7HCc3l3yCETvPBB7EM06GxPPGBEwnCrg9PNh3pUkfFIKhhkTvU6_5KKMAkIqXjWBCQeyDg2__8fVMJMXU140FibZH_8T5-2K0f_RdR1-J5E/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;8-nested-case-upto-10-levels&quot; width=&quot;186&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 8-Nested-Case-Upto-10-Levels&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
If nesting is exceeding 10 levels, then SQL Server throws an error.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Declare @x int
set @x = 1
Select 
case when @x &amp;lt;= 100 then  -- Level 1
case when @x &amp;lt;= 90 then -- Level 2
case when @x &amp;lt;= 80 then -- Level 3
    case when @x &amp;lt;= 70 then -- Level 4
        case when @x &amp;lt;= 60 then -- Level 5
            case when @x &amp;lt;= 50 then -- Level 6
                case when @x &amp;lt;= 40 then -- Level 7
                   case when @x &amp;lt;= 30 then --Level 8
                     case when @x &amp;lt;= 20 then--Level 9
                       case when @x&amp;lt;= 10 then--Level 10
                          case when @x &amp;lt;= 11 then -- 11
                             100
End End End End End End End End End End 
End as &quot;Nested Case&quot;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;b&gt;Msg 125, Level 15, State 4, Line 14&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;Case expressions may only be nested to level 10.&lt;/b&gt;&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/05/nested-case-statement-in-sql-server_15.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhk44scpKgWj-bFfLpS4waYPuZZ_GBSqt9Rkcy7WZpd4hsGM99P4j5cBK8WUL9SmbAiFPPyzjS3N6gbHBmCXqL5hfusuYAyG8We43X3Vn9D4-BQc_DQ5vufPQaFy-kCXWISLL9RgtQrZAPt/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-6528621539046473178</guid><pubDate>Sun, 07 May 2017 14:24:00 +0000</pubDate><atom:updated>2018-01-11T05:22:03.508-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server select into temp table</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Many a times we get an output, and then query the output further. In such scenarios instead of writing the entire query repeatedly, and then improvising it or filtering it differently, we can dump the output of the main query into a temporary table i.e. Select into Temp table. Later we can query the temporary table &amp;amp; improvise the outputs as needed.&lt;br /&gt;
&lt;br /&gt;
Let us create the sample tables.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;CREATE TABLE EMP
       (EMPNO Integer Primary Key,
        ENAME Varchar(15),
        JOB Varchar(9),
        MGR Integer,
        HIREDATE datetime,
        SAL Integer,
        COMM Integer,
        DEPTNO Integer);

INSERT INTO EMP VALUES
        (7369, &#39;SMITH&#39;,  &#39;CLERK&#39;,     7902, &#39;12/17/80&#39;,
        800, NULL, 20);
INSERT INTO EMP VALUES
        (7499, &#39;ALLEN&#39;,  &#39;SALESMAN&#39;,  7698,
        &#39;5/20/81&#39;,1600,  300, 30);
INSERT INTO EMP VALUES
        (7521, &#39;WARD&#39;,   &#39;SALESMAN&#39;,  7698,
        &#39;5/22/81&#39;, 1250,  500, 30);
INSERT INTO EMP VALUES
        (7566, &#39;JONES&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;4/2/81&#39;,  2975, NULL, 20);
INSERT INTO EMP VALUES
        (7654, &#39;MARTIN&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/28/81&#39;, 1250, 1400, 30);
INSERT INTO EMP VALUES
        (7698, &#39;BLAKE&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;5/1/81&#39;,  2850, NULL, 30);
INSERT INTO EMP VALUES
        (7782, &#39;CLARK&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;6/9/81&#39;,  2450, NULL, 10);
INSERT INTO EMP VALUES
        (7788, &#39;SCOTT&#39;,  &#39;ANALYST&#39;,   7566,
        &#39;12/9/82&#39;, 3000, NULL, 20);
INSERT INTO EMP VALUES
        (7839, &#39;KING&#39;,   &#39;PRESIDENT&#39;, NULL,
        &#39;11/17/81&#39;, 5000, NULL, 10);
INSERT INTO EMP VALUES
        (7844, &#39;TURNER&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/8/1981&#39;,  1500,    0, 30);
INSERT INTO EMP VALUES
        (7876, &#39;ADAMS&#39;,  &#39;CLERK&#39;,     7788,
        &#39;1/12/83&#39;, 1100, NULL, 20);
INSERT INTO EMP VALUES
        (7900, &#39;JAMES&#39;,  &#39;CLERK&#39;,     7698,
        &#39;12/3/81&#39;,   950, NULL, 30);
INSERT INTO EMP VALUES
        (7902, &#39;FORD&#39;,   &#39;ANALYST&#39;,   7566,
        &#39;12/3/81&#39;,  3000, NULL, 20);
INSERT INTO EMP VALUES
        (7934, &#39;MILLER&#39;, &#39;CLERK&#39;,     7782,
        &#39;1/23/82&#39;, 1300, NULL, 10);


CREATE TABLE DEPT
       (DEPTNO INTEGER Primary Key,
        DNAME VARCHAR(14),
        LOC VARCHAR(13) );

INSERT INTO DEPT VALUES
        (10,&#39;ACCOUNTING&#39;,&#39;NEW YORK&#39;);
INSERT INTO DEPT VALUES (20,&#39;RESEARCH&#39;,&#39;DALLAS&#39;);
INSERT INTO DEPT VALUES
        (30,&#39;SALES&#39;,&#39;CHICAGO&#39;);
INSERT INTO DEPT VALUES
        (40,&#39;OPERATIONS&#39;,&#39;BOSTON&#39;);&lt;/pre&gt;
&lt;br /&gt;
Now we will write a complex looking select statement as shown here –&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, emp.deptno, sal, 
           case when sal &amp;gt;= 5000 then &#39;Grade A&#39;
                when sal &amp;gt;= 3000 then &#39;Grade B&#39;
                when sal &amp;gt;= 2500 then &#39;Grade C&#39;
                when sal &amp;gt;= 2000 then &#39;Grade D&#39;
                when sal &amp;gt;= 1000 then &#39;Grade E&#39;
                else
                &#39;Grade F&#39;
            end as Sal_Grade,
            datepart(yy, hiredate) as Year_Of_Hiredate,
            DName,
           Sal + IsNull(Comm,0) as Total,
           Case
            when Comm is null or Comm = 0 then &#39;Commission not provided&#39;
            when Comm is not null then &#39;Commission provided&#39;
            End as Commission_Status,
               SubString(Loc,1,1) as Location_ID
from emp join dept
on Emp.deptno = Dept.deptno&lt;/pre&gt;
&lt;br /&gt;
The output of this query is as as follows –&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;complex-select-output&quot; border=&quot;0&quot; height=&quot;263&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGN5XooEljdfKiSDlvrAM8ZUG_Q_Ient5xVwxO855YpiXIbygNNi6gotpVb3HjkiFWL1Em8SPyoEITY5lXBJ-BsGqdbyEHE79XIe0GyaNWwfy7i1bC4IdLq0d4m1LqlgI9vHcVdl0oAi2I/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;complex-select-output&quot; width=&quot;574&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
In this query, we have used the following techniques:&lt;br /&gt;
&lt;br /&gt;
1. Two Case Functions&lt;br /&gt;
2. Date Function&lt;br /&gt;
3. IsNull Function&lt;br /&gt;
4. Substring Function&lt;br /&gt;
5. Inner Join&lt;br /&gt;
&lt;br /&gt;
Now improvise this output. Put this output into a local temporary table by issuing the following query:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Select * into #Emp_Info
from(select ename, emp.deptno, sal, 
           case when sal &amp;gt;= 5000 then &#39;Grade A&#39;
                when sal &amp;gt;= 3000 then &#39;Grade B&#39;
                when sal &amp;gt;= 2500 then &#39;Grade C&#39;
                when sal &amp;gt;= 2000 then &#39;Grade D&#39;
                when sal &amp;gt;= 1000 then &#39;Grade E&#39;
                else
                &#39;Grade F&#39;
            end as Sal_Grade,
            datepart(yy, hiredate) as Year_Of_Hiredate,
            DName,
           Sal + IsNull(Comm,0) as Total,
           Case
            when Comm is null or Comm = 0 then &#39;Commision not provided&#39;
            when Comm is not null then &#39;Commision provided&#39;
            End as Commission_Status,
               SubString(Loc,1,1) as Location_ID
from emp join dept
on Emp.deptno = Dept.deptno
) as Emp_Dept&lt;/pre&gt;
&lt;br /&gt;
So now these 14 processed rows are the actual records of #Emp_Info table. Therefore now when we will query this table, the inner join, case, date, substring &amp;amp; IsNull functions do not get executed again &amp;amp; again. This will be a big performance boost!&lt;br /&gt;
&lt;br /&gt;
Let’s explore different outputs querying the #Emp_Info table now.&lt;br /&gt;
&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Query 1 – Display records of Grade B employees&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Select * from #Emp_Info
where Sal_Grade = &#39;Grade B&#39;
go

&lt;img alt=&quot;gradeb-employees&quot; border=&quot;0&quot; height=&quot;72&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdXl5zEM_UlKHtI8EBAjs7DwZ4HwUDCM4JceHeIxr4nn3TjZOFC2Ge5CTjMap9DlDKiXRSsRlMhoEtOeKDbwr_K85K5qYVfXprRTN654UegRvkVSbl_WHuMOlGSvy0QsY5qp-AAdq_s0_1/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;gradeb-employees&quot; width=&quot;574&quot; /&gt;&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
&lt;strong&gt;Query 2 – Display grade wise total of salaries&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;pre&gt;Select Sal_Grade, Sum(Sal) as Salary_Sum
from #Emp_Info
Group by Sal_Grade
go

&lt;img alt=&quot;sql-select-into-temp&quot; border=&quot;0&quot; height=&quot;161&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBZOVxqe5RDOsRvGl-TKXIlZoTqO2n3_Q-HDVSTpENXyGka4Kr-ke4qhHHXbmXvrtWJysjFDijvXaiheyVWymLtLEA4EgRI89UAu0upkl66GejKBXHkKTs6gMGPCPRiJdHKyzShKggpdEk/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-select-into-temp&quot; width=&quot;175&quot; /&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;strong&gt;Query 3 – Display employee names, totals, DName and year of hiredate for all employees who have joined in 1981.&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Select Ename, DName, Total, Year_of_Hiredate
from #Emp_Info
where Year_of_Hiredate = &#39;1981&#39;&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
&lt;img alt=&quot;sql-select&quot; border=&quot;0&quot; height=&quot;237&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeNHC7daw8IPtywXH42kVW_AXmdcYT6D9b98tA1IK5RC7rcEgBx3AhD51f8gFRlQME-JcOqvmozsmdg1osmXUzCdjL_RN8YQ9jSPc05mjd1Jbcf2ml2ew3rRqlNHm9N4m913Xl4WGmb7T2/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-select&quot; width=&quot;318&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
So as we can see, doing a &lt;strong&gt;T-SQL Select into temp table&lt;/strong&gt; can help us fire additional queries on the output, and in some cases, give a performance boost too&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/09/sql-server-select-into-temp-table_7.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGN5XooEljdfKiSDlvrAM8ZUG_Q_Ient5xVwxO855YpiXIbygNNi6gotpVb3HjkiFWL1Em8SPyoEITY5lXBJ-BsGqdbyEHE79XIe0GyaNWwfy7i1bC4IdLq0d4m1LqlgI9vHcVdl0oAi2I/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-297960529392750235</guid><pubDate>Wed, 31 Aug 2016 13:11:00 +0000</pubDate><atom:updated>2016-09-01T00:06:25.370-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server General</category><title>Importance of RAID in Databases</title><description>&lt;div align=&quot;justify&quot;&gt;
&lt;em&gt;This article was modified on August 31st, 2016.&lt;/em&gt;&lt;br /&gt;
&lt;em&gt;&lt;br /&gt;&lt;/em&gt;
RAID is a disk system that contains multiple disk drives, called an array, to provide greater performance, fault tolerance, storage capacity, at a moderate cost. While configuring your server system, you typically have to make a choice between hardware RAID and software RAID for the server’s internal disk drives&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;img alt=&quot;RAID System&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0816UqZpyTdhi9PUSb7aZCehcCGBfXmxpn9o3mnKZz0FEnjZ_IvPTqTJPa8nwsqaz_liU7eeq1QQHhW809xV4ShG2dI8lXw4BwiIrvjNd8bdb4Ov6-Q2ifIdHyIAhSMJi-p-FQecma4Vi/?imgmax=800&quot; height=&quot;311&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;RAID System&quot; width=&quot;393&quot; /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
RAID systems are widely used as storage solutions to get the best I/O performance, depending&amp;nbsp;whether the application is write intensive or read intensive. DBA RayRankins mentions in his book that for database-related applications, in order to minimize disk head movement and maximize I/O performance, it’s a good practice to spread random I/O’s (data changes) and sequential I/O’s (for the transaction log) across different disk subsystems. I agree and endorse his view, as SQL Server, or for that matter any other database, is very much an I/O intensive system.&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;em&gt;&lt;strong&gt;I will be using SQL Server as an example to explain the importance of RAID in databases, however you can implement these concepts in your choice of database. The concepts more or less, remain the same&lt;/strong&gt;&lt;/em&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
Although RAID is not a part of a database like SQL Server, implementing RAID can directly affect the way SQL Server performs.There are many RAID arrays available such as RAID 0, RAID 1, RAID 3, RAID 4, RAID 5, RAID 6, RAID 10 and RAID 01. In this article, we will discuss the ones you will likely encounter as a SQL Server DBA&amp;nbsp;i.e. RAID levels 0, 1, 5 and 10 and also&amp;nbsp; discuss their advantages and disadvantages from a fault tolerance and performance perspective&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;em&gt;Note: RAID is not a replacement for backups. Backups are very essential for any system.&lt;/em&gt;&lt;br /&gt;
&lt;em&gt;&lt;br /&gt;&lt;/em&gt;&lt;/div&gt;
&lt;h4 align=&quot;justify&quot;&gt;

Different RAID Levels (Advantages and Disadvantages)&lt;/h4&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;
We will discussing only RAID 0, 1, 5 and 10 (database perspective)&amp;nbsp;. &lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;strong&gt;RAID 0 – &lt;/strong&gt;Also known as Disk Striping, RAID 0 does not provide redundancy or fault tolerance but instead writes data to two drives, in an alternating fashion. This provides the best read write I/O performance. If you had 8 chunks of data, for example, chunk 1, 3, 5, and 7 would be written to the first drive, and chunk 2, 4, 6, and 8 would be written to the second drive, but all in a fixed (sequential) order. RAID 0 has a simple design, easier to implement and no overheads for parity. The drawback is that any piece of data is on only one disk, so if one disk fails, data stored within those disks are lost.&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;strong&gt;RAID 1&lt;/strong&gt;- Also known as Disk Mirroring, RAID 1 provides a redundant, identical copy of a selected disk and thus provides good fault tolerance. It can be implemented with 2 drives. The disadvantage is that it has a big storage overhead and a high cost/capacity ratio&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;strong&gt;RAID 5&lt;/strong&gt; - Also known as Disk Striping with Parity, stripes data across multiple drives and writes parity bits across drives. Data redundancy is provided by the parity information. It can be implemented with 3 or more disks and is a popular choice amongst DBA’s. Since data and parity information are arranged on the disk array, two types of information are always on different disks. If one disk fails, just replace it with a new disk and the array rebuilds itself. RAID 5 has a higher read rate and makes good use of capacity. The drawback of RAID 5 is slower write rates and slow rebuild times.&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;strong&gt;RAID 10&lt;/strong&gt; - Also known as mirroring with striping, RAID 10 is a combination of RAID1 + RAID0. RAID 10 uses a striped array of disks that are then mirrored to another identical set of striped disks. This array level uses at least four hard disks and additional disks must be added in even numbers. The data is first placed into mirrored pairs at the lower level. Next, the controller selects a member from each mirrored pair and stripes the data into a new logical volume. Since RAID 10 writes in a random fashion, it provides best performance with a write-intensive application (like video editing). The drawback is that it is expensive.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h4 align=&quot;justify&quot;&gt;

Which RAID is Suitable for my Database?&lt;/h4&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;
Now that you have an overview of RAID levels, let’s look at which RAID is suitable for a database. The answer to this question depends on a variety of factors. Do you want availability, performance or cost? What are your requirements for fault tolerance and performance? Here’s a quick snapshot of the performance and fault tolerance provided by RAID&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;strong&gt;&lt;img alt=&quot;sqlserver-raid-performance&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA5VxL0B9fPkeIXaOuVHd-6XVGAaE5xkDPRQ73aYt9pfgZy88vynFWunay8jJjccqPZMWHVOExtMKtv7tgEb9I1pD2XqilnDwF9fe7MgBJ8NPXaKp8t9mUcRPk0WDVPBQ6-5W_VSkQmca0/?imgmax=800&quot; height=&quot;125&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sqlserver-raid-performance&quot; width=&quot;554&quot; /&gt;&lt;/strong&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
When it comes to a database like SQL Server, no one RAID level will suit your need. In most cases, SQL Server performs large reads and small writes. So for databases, where write operations are more, RAID 5 is not a good choice. On the contrary, RAID 10 is a good option for databases with more write operations. &lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
Here are some points and best practices to keep in mind while deciding the RAID system for your database. &lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
Your Data, Logs, tempdb, and backups should be on separate physical drives or a set of disks (array).&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
RAID1 is often chosen to store operating systems, binaries, index file groups and database transaction log files. Critical to log and index performance is fault tolerance and a good write speed. &lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
Since log file are written sequentially and are read only for recovery operations, recommended RAID for Log Files is RAID 1 or 10. If your RAID 1 is at a 100% usage, choose RAID 10 for better performance.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
For data files with random access and read heavy data volumes, striping is important. So recommended RAID is 5 or 10. &lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
For data files which require good write performance, RAID 10 is recommended. Use a battery backed caching RAID controller for better write performance&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
For tempdb files with good read/write performance RAID 0, 1 or 10 is recommended. Although tempdb contains temporary data and DBA’s often go in for RAID 0 for tempdb, keep in mind that SQL Server requires tempdb to carry out many of its activities. So if you want your system to be always available, rethink RAID 0.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
Putting log files or tempdb on a RAID 5 array is not recommended, since RAID 5 does not perform well for write operations. DBA&#39;s although have conflicting opinions over this point.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;     &lt;div align=&quot;justify&quot;&gt;
Choose small fast drives, over large slow drives.&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div align=&quot;justify&quot;&gt;
Make sure you do your own research, so you can make an informed decision! In a real scenario, you may not have the luxury of deciding your server configurations due to the cost associated with it. So keeping these points in mind, may help you in such scenarios.&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div align=&quot;justify&quot;&gt;
Please use the comments section and share your opinions!&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2013/09/importance-of-raid-in-databases.html</link><author>noreply@blogger.com (Suprotim Agarwal)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0816UqZpyTdhi9PUSb7aZCehcCGBfXmxpn9o3mnKZz0FEnjZ_IvPTqTJPa8nwsqaz_liU7eeq1QQHhW809xV4ShG2dI8lXw4BwiIrvjNd8bdb4Ov6-Q2ifIdHyIAhSMJi-p-FQecma4Vi/s72-c?imgmax=800" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-365898056329600005</guid><pubDate>Fri, 26 Aug 2016 09:51:00 +0000</pubDate><atom:updated>2016-09-01T00:08:33.085-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">SQL Server Administration</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Default Port</title><description>In this article, we are going to explore the default port number of SQL Server required for getting connected to different applications.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;What is a Port?&lt;/strong&gt; It is an endpoint of communication in an &lt;a href=&quot;https://en.wikipedia.org/wiki/Operating_system&quot;&gt;operating system&lt;/a&gt;. A port is always associated with an &lt;a href=&quot;https://en.wikipedia.org/wiki/IP_address&quot;&gt;IP address&lt;/a&gt; of a host, and the &lt;a href=&quot;https://en.wikipedia.org/wiki/Network_protocol&quot;&gt;protocol&lt;/a&gt; type of the communication, thereby completing the destination or origination address of a communication session. A port is identified for each address and protocol by a 16-bit number, commonly known as the &lt;strong&gt;port number&lt;/strong&gt;.&lt;br /&gt;
When front end applications want to connect to SQL Server, port number is essential. &lt;br /&gt;
&lt;br /&gt;
The default port number of SQL Server is &lt;b&gt;1433&lt;/b&gt;.&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;How to get the port number in SQL Server?&lt;/span&gt;&lt;/h2&gt;
&lt;i&gt;Note -&lt;/i&gt;&lt;i&gt; The steps are shown through SQL Server 2012 environment. They are largely applicable to SQL Server 2014 too.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Step 1: Open the &lt;u&gt;SQL Server Configuration Manager&lt;/u&gt; window through Start &amp;gt; All Programs &amp;gt; Microsoft SQL Server 2012 &amp;gt; Configuration Tools&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;sccm-navigation&quot; border=&quot;0&quot; height=&quot;242&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsYWuONLNxUlRTTbYTSLntwkGF3S7y4xK_ZY1iFxjI5twVND56OA_I5EsPKM1KJftGqkjbk1SF_QWNm8WQsqBPYCiU1wksqoSTWGACEqhcfKPOlcum4czwbNk_Slsndk7qFjsMNoBRMcE9/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sccm-navigation&quot; width=&quot;255&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Step 2: Explore &lt;b&gt;SQL Native Client 11.0 Configuration (32bit)&lt;/b&gt; &lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;img alt=&quot;sql-native-client-configuration&quot; border=&quot;0&quot; height=&quot;221&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhp94byiSW6ISkgJODInyDbGIwO-VIzFVCe9IGU3bsM6PUj-LOUE6l6w58foodjPUXiuIv6hPXWSysNvtP7ZYDoQzMU0ybTVs0tJaYXoLINTGW4uc0mAY4o5BI4379DVPTP26QD_5aOw2aA/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-native-client-configuration&quot; width=&quot;518&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Step 3: Click on &lt;b&gt;Client Protocols&lt;/b&gt; option within it&amp;nbsp; –&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;client-protocols&quot; border=&quot;0&quot; height=&quot;222&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKaTSmuLKDcQgaqqesbpvsafi7vNJ9k9rqzbLDrBU5APlVDfo3s1PqHONmjjrM4q0XKRgvhWnRYQks1K4C_ey7ve0m7MmQYOV1gGA3uHlVmtiQMghIXldrqUrghlKOGcjREHULUbcr-C7s/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;client-protocols&quot; width=&quot;279&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Step 4: Double click on &lt;b&gt;TCP/IP&lt;/b&gt; from the right hand side pane &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;tcp-ip&quot; border=&quot;0&quot; height=&quot;163&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiU6QGJQlTGRGgKSNq41RmfNSZP-aj0mXxIVGYMX3bFO4m10gR1VYXOKeCmSICFeMPx_pUICCG3u2cuW-5aZQxKT6XTRYxy0t6QDxqAM_b9r3PPCb59G_AKSzKg7oG82JPtc5vK5IzKNs9k/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;tcp-ip&quot; width=&quot;574&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
We will get to know the &lt;b&gt;Default Port&lt;/b&gt; as shown here&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;1433-default-port&quot; border=&quot;0&quot; height=&quot;156&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1RPby0f3pTnKOb0ruROgeTohW6GCCBwem2BDLp58DXX3Lq_Lao8mGzhPqqMrvTv6mBnIxKI7FywsYoOGTkXFlY0MIqBX7GwH05FeF8wXw_KwKg7W85Os5oknsGMHZLOxnATHvo3nqreHZ/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;1433-default-port&quot; width=&quot;270&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
The default port &amp;gt; 1433 port is the official Internet Assigned Number Authority (IANA) socket number for SQL Server. Client systems use TCP 1433 to connect to the database engine; SQL Server Management Studio (SSMS) uses the port to manage SQL Server instances across the network. You can reconfigure SQL Server to listen on a different port, but 1433 is by far the most common implementation.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Some other default SQL Server ports&lt;/strong&gt;:&lt;br /&gt;
&lt;br /&gt;
TCP 1434 – For Dedicated Admin Connection&lt;br /&gt;
UDP 1434 – For SQL Server Named Instance&lt;br /&gt;
TCP 2383 – For Default port of SSAS&lt;br /&gt;
TCP 2382 – For Named instances of SSAS&lt;br /&gt;
TCP 135 – For SSIS &amp;amp; T-SQL Debugger&lt;br /&gt;
TCP 80 and 443 – For SSRS&lt;br /&gt;
TCP 4022 – For Service Broker&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;other-default-ports&quot; border=&quot;0&quot; height=&quot;154&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXbzTUl_xOJ6kakeTUGDET31XHYWEVpHyU4xddzxr2B9BgCe-PUpSazHGD7HlaPv-h5vIYD7-B64FVhXN32ExRVk4zhqNeqvDBb-LUTT7nBwuYye9srfzOXzDJWWRiTaMcXf1IUhrvLpB2/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;other-default-ports&quot; width=&quot;548&quot; /&gt;</description><link>http://www.sqlservercurry.com/2016/08/sql-server-default-port_30.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsYWuONLNxUlRTTbYTSLntwkGF3S7y4xK_ZY1iFxjI5twVND56OA_I5EsPKM1KJftGqkjbk1SF_QWNm8WQsqBPYCiU1wksqoSTWGACEqhcfKPOlcum4czwbNk_Slsndk7qFjsMNoBRMcE9/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-2318391334049262996</guid><pubDate>Thu, 18 Aug 2016 03:22:00 +0000</pubDate><atom:updated>2016-08-30T02:56:19.300-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Update statement with JOIN</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In this article, we are specifically going to see a practical usage of the UPDATE statement in SQL Server when the condition is based on JOIN of another table.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;CREATE TABLE EMP
       (EMPNO Integer Primary Key,
        ENAME Varchar(15),
        JOB Varchar(9),
        MGR Integer,
        HIREDATE datetime,
        SAL Integer,
        COMM Integer,
        DEPTNO Integer);
go
INSERT INTO EMP VALUES
        (7369, &#39;SMITH&#39;,  &#39;CLERK&#39;,     7902, &#39;12/17/80&#39;,
        800, NULL, 20);
INSERT INTO EMP VALUES
        (7499, &#39;ALLEN&#39;,  &#39;SALESMAN&#39;,  7698,
        &#39;5/20/81&#39;,1600,  300, 30);
INSERT INTO EMP VALUES
        (7521, &#39;WARD&#39;,   &#39;SALESMAN&#39;,  7698,
        &#39;5/22/81&#39;, 1250,  500, 30);
INSERT INTO EMP VALUES
        (7566, &#39;JONES&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;4/2/81&#39;,  2975, NULL, 20);
INSERT INTO EMP VALUES
        (7654, &#39;MARTIN&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/28/81&#39;, 1250, 1400, 30);
INSERT INTO EMP VALUES
        (7698, &#39;BLAKE&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;5/1/81&#39;,  2850, NULL, 30);
INSERT INTO EMP VALUES
        (7782, &#39;CLARK&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;6/9/81&#39;,  2450, NULL, 10);
INSERT INTO EMP VALUES
        (7788, &#39;SCOTT&#39;,  &#39;ANALYST&#39;,   7566,
        &#39;12/9/82&#39;, 3000, NULL, 20);
INSERT INTO EMP VALUES
        (7839, &#39;KING&#39;,   &#39;PRESIDENT&#39;, NULL,
        &#39;11/17/81&#39;, 5000, NULL, 10);
INSERT INTO EMP VALUES
        (7844, &#39;TURNER&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/8/1981&#39;,  1500,    0, 30);
INSERT INTO EMP VALUES
        (7876, &#39;ADAMS&#39;,  &#39;CLERK&#39;,     7788,
        &#39;1/12/83&#39;, 1100, NULL, 20);
INSERT INTO EMP VALUES
        (7900, &#39;JAMES&#39;,  &#39;CLERK&#39;,     7698,
        &#39;12/3/81&#39;,   950, NULL, 30);
INSERT INTO EMP VALUES
        (7902, &#39;FORD&#39;,   &#39;ANALYST&#39;,   7566,
        &#39;12/3/81&#39;,  3000, NULL, 20);
INSERT INTO EMP VALUES
        (7934, &#39;MILLER&#39;, &#39;CLERK&#39;,     7782,
        &#39;1/23/82&#39;, 1300, NULL, 10);
go

CREATE TABLE DEPT
       (DEPTNO INTEGER Primary Key,
        DNAME VARCHAR(14),
        LOC VARCHAR(13) );
go
INSERT INTO DEPT VALUES
        (10,&#39;ACCOUNTING&#39;,&#39;NEW YORK&#39;);
INSERT INTO DEPT VALUES (20,&#39;RESEARCH&#39;,&#39;DALLAS&#39;);
INSERT INTO DEPT VALUES
        (30,&#39;SALES&#39;,&#39;CHICAGO&#39;);
INSERT INTO DEPT VALUES
        (40,&#39;OPERATIONS&#39;,&#39;BOSTON&#39;);&lt;/pre&gt;
&lt;br /&gt;
Let us see the two tables.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from emp
go
select * from dept
go&lt;/pre&gt;
&lt;br /&gt;
&lt;img alt=&quot;emp-dept-table&quot; border=&quot;0&quot; height=&quot;430&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIlmE0V7uuUenCVV2kpk1UiSdnT2zrTXUA-EWBdD9kR-robyLzKV6juDwYq5pPl9ERiyTCf3f4UzJYcXhyCC8nOXkVfBm46xwwkNcgQkQLibWQnzB262oTTPjnqmSELNQPh1Uuk1lKQAQb/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;emp-dept-table&quot; width=&quot;580&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Here we can see that this is a typical parent-child table relationship. Many a times, the end user wants to see the Employee Names (Enames) and Department Names (Dnames). But for that, they need to surrender to the inner join technique. Right now, only 14 rows are in emp table and 4 rows in dept.&lt;br /&gt;
&lt;br /&gt;
But in a real time production environment, the number of records will be much higher. So this may result into a performance overhead. Therefore the DBA in such scenarios may decide to add the DName column in Emp table itself to eliminate the a JOIN overhead.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;strong&gt;Note: &lt;/strong&gt;&lt;/i&gt;&lt;i&gt;Here we are moving towards an intentional De-Normalization technique.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The following ALTER Table command is used for that.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table Emp
Add Dname Varchar(40)&lt;/pre&gt;
&lt;br /&gt;
But now the problem is that for existing records if we see the DName colum, then it will be Null. Let us check it.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from emp&lt;/pre&gt;
&lt;br /&gt;
&lt;img alt=&quot;sql-adding-dname-column&quot; border=&quot;0&quot; height=&quot;310&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqmqU5kh8FnH2V1zhAXu0F3BGPlPB0crqdkpjuRzBef-VmpYOkdHq4ski5bVcI1mXgaqHgd_46F2mUNTdiskk1ejGUfnTwbQSMlflaFX901JQdFnIZSPz_80RXI5XQ0bS6YQp7TJtFaxzi/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-adding-dname-column&quot; width=&quot;574&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
So now we want to update each Dname as per the Dname of Dept table. For this we will issue the &lt;u&gt;&lt;strong&gt;Update statement with join.&lt;/strong&gt;&lt;/u&gt;&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Update Emp 
set Dname  = Dept.DName
From Emp, Dept
where Emp.Deptno = Dept.Deptno&lt;/pre&gt;
&lt;br /&gt;
Technique: Here the update technique with join is used in the following sequential steps.&lt;br /&gt;
&lt;br /&gt;
1. Every record of Emp is taken.&lt;br /&gt;
2. Its deptno is matched with deptno of Dept table. &lt;br /&gt;
3. The corresponding DName of Dept table is assigned to that row.&lt;br /&gt;
4. Next row of Emp is taken.&lt;br /&gt;
5. Step numbers 2 &amp;amp; 3 are repeated.&lt;br /&gt;
6. This process continues till the last row is reached by Emp table.&lt;br /&gt;
&lt;br /&gt;
So now let us see the Emp table again.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from emp&lt;/pre&gt;
&lt;br /&gt;
&lt;img alt=&quot;after-update-with-sql-join&quot; border=&quot;0&quot; height=&quot;303&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4QlzJk7w_p-gz1qRvZOAaUjn2WD_gUjPPdd-s0n0t_pmXnU22QrYapbrcopPTFBRzOWZQ6OKddsYHoWXRYk8_Xk6Hkz42bk6fNixhi-y6KEaA3NWbAgpYEwKaAb1sg7hFbyJ1Rxa-PoSD/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;after-update-with-sql-join&quot; width=&quot;573&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
and that’s how we can use the &lt;strong&gt;Update statement with JOIN in SQL Server.&lt;/strong&gt;&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/07/sql-server-update-statement-with-join_17.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIlmE0V7uuUenCVV2kpk1UiSdnT2zrTXUA-EWBdD9kR-robyLzKV6juDwYq5pPl9ERiyTCf3f4UzJYcXhyCC8nOXkVfBm46xwwkNcgQkQLibWQnzB262oTTPjnqmSELNQPh1Uuk1lKQAQb/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-2756636394000679215</guid><pubDate>Mon, 08 Aug 2016 04:10:00 +0000</pubDate><atom:updated>2016-08-07T21:13:45.478-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Substring with CharIndex</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In this article we are going to explore the T-SQL function CharIndex and also how to use it with another T-SQL function Substring().&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;CharIndex:&lt;/strong&gt; This function returns the location of a substring in a string. By default, it is not case sensitive and is useful to check the position of a particular character or digit in the string. I have seen this function being used in product codes, different types of IDs for validation purpose, or to get some business understanding of that code/ID. Here’s the syntax:&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;CHARINDEX( Substring or Character, string, [start_position] )&lt;/pre&gt;
&lt;br /&gt;
where..&lt;br /&gt;
&lt;br /&gt;
Substring or Character - The string that you want to find. It has to be within string data type family such as char or varchar only.&lt;br /&gt;
String - The string or number or an alphanumeric value to search within.&lt;br /&gt;
start_position - Optional. The position in &lt;i&gt;string&lt;/i&gt; where the search will start. The first position is 1.&lt;br /&gt;
&lt;br /&gt;
The function returns &lt;b&gt;bigint&lt;/b&gt;&lt;b&gt; &lt;/b&gt;if the &lt;i&gt;expressionToSearch&lt;/i&gt; is of varchar(max), nvarchar(max), or varbinary(max) data types; otherwise, it retuns an &lt;b&gt;int&lt;/b&gt;.&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Substring with CharIndex examples:&lt;/span&gt;&lt;/h2&gt;
&lt;pre&gt;select charindex(&#39;C&#39;,&#39;ABCDEF&#39;,1) 
-- Returns 3

select charindex(&#39;C&#39;,&#39;ABCDEF&#39;) 
-- Still returns 3 as start_position is option, default is 1

select charindex(&#39;c&#39;,&#39;ABCDEF&#39;,1) 
-- By default not case sensitive, so returns 3

select charindex(&#39;c&#39;,&#39;ABCDEF&#39; COLLATE Latin1_General_CS_AS) 
–- Returns 0 as lowercase c is not found.

select charindex(&#39;Z&#39;,&#39;ABCDEF&#39;,1) 
-- Returns 0 as there is no Z character

select charindex(&#39;A&#39;,&#39;ABCDAEFG&#39;,2) 
-- Returns the second position of A, i.e. 5

select charindex(&#39;A&#39;,&#39;ABCDAEFG&#39;,9) 
-- Returns 0 as there is no ninth position there is no A

select charindex(&#39;4&#39;,123456) 
-- Searching from pure numbers, returns 4 as 4 is on fourth position

select charindex(&#39;curry&#39;,&#39;sqlservercurry.com&#39;) 
-- It considers the first character of string curry, 
-- i.e. c and then checks the first occurrence, so returns 10&lt;/pre&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Using CharIndex with Substring:&lt;/span&gt;&lt;/h3&gt;
First let us check the functionality of the Substring function. It extracts a part of the string from the specified position.&lt;br /&gt;
&lt;br /&gt;
Syntax:&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Substring(String, Position or Index, Number of characters to extract)&lt;/pre&gt;
&lt;pre&gt;select substring(&#39;abcdef&#39;, 2, 3) 
-- Returns bcd as 2 is from which position and 3 is number of characters to extract&lt;/pre&gt;
&lt;br /&gt;
Now the best usage of &lt;strong&gt;CharIndex with Substring&lt;/strong&gt; is to create a functionality of “Text to Columns”.&lt;br /&gt;
&lt;br /&gt;
That means many a times the names are in the format of “FirstName &lt;i&gt;whitespace&lt;/i&gt; LastName” in the same column itself. In such cases, the need is to separate First Name in one column, and Last Name in another column for display purposes.&lt;br /&gt;
&lt;br /&gt;
Consider the following example.&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;create table Authors
(AuthorID Varchar(2),
 AuthorName Varchar(60)
 )
 go
Insert into Authors Values(&#39;A1&#39;,&#39;Suprotim Agarwal&#39;)
Insert into Authors Values(&#39;A2&#39;,&#39;Mahesh Sabnis&#39;)
Insert into Authors Values(&#39;A3&#39;,&#39;Mandar Mulay&#39;)
go
select * from Authors
go

&lt;img alt=&quot;sql-default-author-table&quot; border=&quot;0&quot; height=&quot;126&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsFacPRvnIzHEh7Kl4xvvoTu1Wy2cHb0tt5Wa74vEwiYgQ1Dl2YSbx4HtqSCcjxsRCf9J7raoBGlotevaPPobBMZQ6hDApVjTofaRION5bTDpthW2MVTb1D6EN9RqlR5nNrQwCb86tjuaN/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-default-author-table&quot; width=&quot;366&quot; /&gt;&lt;/pre&gt;
&lt;br /&gt;
Now let us say we want to display first name and last name in different columns. For that, we will use the substring function and within it, we will use CharIndex function to know the position number of white space.&lt;br /&gt;
&lt;br /&gt;
See the following query:&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;select substring(AuthorName,1, charindex(&#39; &#39;,AuthorName)) as [First Name],
substring(AuthorName,(charindex(&#39; &#39;,AuthorName)) + 1, len(AuthorName)) as [Last Name]
from Authors
go&lt;/pre&gt;
&lt;br /&gt;
&lt;img alt=&quot;substring-with-charindex&quot; border=&quot;0&quot; height=&quot;105&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOxtfeY6k7wc5gXtVSqcgsVo_QXVEVvWp8ZwC6FLqu1AOCeMRXN7tSmj3eTNOYM1rlE0iIAg-rCQndTpRkMHPBZpbKgJgzisZezXnr0teN-n9KjkxXJQP3UbHDBnqSZGNJlMzLNTess2dO/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;substring-with-charindex&quot; width=&quot;167&quot; /&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First Name - substring(AuthorName,1,&lt;b&gt; &lt;/b&gt;charindex(&#39; &#39;,AuthorName)) means from the first position till the first white space comes extract all the characters.&lt;br /&gt;
&lt;br /&gt;
Last Name - substring(AuthorName,(charindex(&#39; &#39;,AuthorName)) + 1,&lt;b&gt; &lt;/b&gt;len(AuthorName)) means to extract from the first white space + 1. Then to extract all remaining characters the len function is used.&lt;br /&gt;
&lt;br /&gt;
And that’s how we use the &lt;strong&gt;SQL Server T-SQL Substring&lt;/strong&gt; function, as well as &lt;strong&gt;Substring with CharIndex&lt;/strong&gt;.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/08/sql-server-substring-with-charindex_7.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsFacPRvnIzHEh7Kl4xvvoTu1Wy2cHb0tt5Wa74vEwiYgQ1Dl2YSbx4HtqSCcjxsRCf9J7raoBGlotevaPPobBMZQ6hDApVjTofaRION5bTDpthW2MVTb1D6EN9RqlR5nNrQwCb86tjuaN/s72-c?imgmax=800" height="72" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1876044819603740685</guid><pubDate>Mon, 25 Jul 2016 16:54:00 +0000</pubDate><atom:updated>2016-07-25T09:54:36.947-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Delete Duplicate Rows</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
There can be two types of duplication of rows in a table&lt;br /&gt;
&lt;br /&gt;
1. Entire row getting duplicated because there is no primary key or unique key.&lt;br /&gt;
2. Only primary key or unique key value is different, but remaining all values are same.&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Scenario 1: Delete duplicate rows without primary key or unique key.&lt;/span&gt;&lt;/h2&gt;
Let us create the following example.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table customers1
(CustId Int,
 CustName Varchar(20),
 CustCity Varchar(20),
 Passport_Number Varchar(20))
 go
Insert into customers1 Values(1, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
Insert into customers1 Values(2, &#39;Martin&#39;, &#39;London&#39;, &#39;L873X92&#39;)
Insert into customers1 Values(3, &#39;Smith&#39;, &#39;New York&#39;, &#39;N293Y99&#39;)
Insert into customers1 Values(1, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
go
select * from customers1
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-row-duplicate&quot; border=&quot;0&quot; height=&quot;125&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWwnfmtGIDdWd8SrMSNk7p-d0SUykT0JJd2Qqqhi-_50pUBYTJbaPA7UXrfqnIJA6TTvvbKfeVmFku02VZnqX8Z_wAVzmREu1upM0tOgsd-zbJzXe0tNyrPS8Mf0-0Uc9TZXSVgCoXVSVY/?imgmax=800&quot; style=&quot;background-image: none; border-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-row-duplicate&quot; width=&quot;313&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
We want remove one of the duplicate records of John.&lt;br /&gt;
&lt;br /&gt;
By issuing the following summary query, we can see which see which records are duplicate.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers1
Group by Custid,CustName, CustCity, Passport_Number
Having count(*) &amp;gt; 1&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;duplicate-row&quot; border=&quot;0&quot; height=&quot;90&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGHSTKiDLzJXyJcP-uGJc9kx4Skk5GsPSc8kmH7HKVSE2wd0BOSkVsYJKopugNEd581kyllwhCPLEKqa5qnjwLfWQFGg4oHEME_VQHtwnIGDxcPh066WznCMQBpKR7apFkLpiKBpKmh8eg/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;duplicate-row&quot; width=&quot;304&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Now we will add this row to a local temporary table.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Select * into #Temp_customers1 from customers1 where 1 = 2&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into #Temp_customers1
select * from customers1
Group by Custid,CustName, CustCity, Passport_Number
Having count(*) &amp;gt; 1&lt;/pre&gt;
&lt;br /&gt;
Now the situation is that the duplicate row is in the local temporary table. All we need to now is to delete records from main table customers1 as per matching custid of the local temporary table.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Delete from customers1
where custid in (select Custid from #Temp_customers1)&lt;/pre&gt;
&lt;br /&gt;
Will the above query work? Not entirely, as by using the above query, we lost all the duplicate records!! Let us see the table again.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers1
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;img alt=&quot;deleting-all-duplicate-rows&quot; border=&quot;0&quot; height=&quot;111&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8_uCjcMc4Ltnmj9QAjlVk3sD9ICUYQ2c2jzTQOtkDN3SQQ2fTS8A_u8KsSbzm1vD9G0rDejTrzjnJwrWQui66Njqect2tBskSqLAIqWtCVJa5SPytmbTOCoAEAWId30RT0rzW1MsGYj8U/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;deleting-all-duplicate-rows&quot; width=&quot;312&quot; /&gt;&lt;/pre&gt;
&lt;br /&gt;
Now to keep one record of John, we will take help of the local temporary table again. Let us add the same record from temporary table into customers1 table.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Customers1
select * from #Temp_customers1
go&lt;/pre&gt;
&lt;br /&gt;
Finally we got a single record of John at the end. Let us confirm by seeing the Customers1 table.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers1
go

&lt;img alt=&quot;removing-duplicate-row&quot; border=&quot;0&quot; height=&quot;135&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhH9C6VtnEkAtElYIDfADtHjcT5MdtAbdbdWzxj7FGC7L1seb7od4iJlt_mSGZjyxjPVBjTTffqSktKgmBFnXs2XrUMcFAQhIqYZedv-RYWJPfIZ7_NI6oax8f8-8BoDXikC2G7c0IdoQVg/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;removing-duplicate-row&quot; width=&quot;323&quot; /&gt;&lt;/pre&gt;
&lt;br /&gt;
Once done, we can drop the local temporary table.&lt;br /&gt;
&lt;h2&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Scenario 2: Delete duplicate rows where primary key or unique key value is different but remaining values are same.&lt;/span&gt;&lt;/h2&gt;
Let us create the following example.

&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table customers2
(CustId Int Primary Key,
 CustName Varchar(20),
 CustCity Varchar(20),
 Passport_Number Varchar(20))
 go
Insert into customers2 Values(1, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
Insert into customers2 Values(2, &#39;Martin&#39;, &#39;London&#39;, &#39;L873X92&#39;)
Insert into customers2 Values(3, &#39;Smith&#39;, &#39;New York&#39;, &#39;N293Y99&#39;)
Insert into customers2 Values(4, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
Insert into customers2 Values(5, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
select * from customers2
go&lt;/pre&gt;
&lt;br /&gt;
Here is the same customer’s record, but this time John’s record has been added thrice with different customer ids but same Passport number! &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;duplicate-rows-different-custids&quot; border=&quot;0&quot; height=&quot;153&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisk2aGU1P9bphjAPh1L98oQva_lnAmaV_QkEevcjGN5zj_sKIhFT2F_U9OnpaAFZ2iXF3DCxaa27b4Wlja_tEC4dcrtpB2Ohveehfps8q7Ei8fqX3-TLuVf77AhLUkvQGhrv1xEvx9L_XC/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;duplicate-rows-different-custids&quot; width=&quot;310&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;b&gt;
Scenario 2.a: Delete Duplicate rows but keep one using CTE&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
We need to use the technique of Self Join initially to check for duplicate records containing different custid but same passport number.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select distinct a.*
from customers2 a join customers2 b
on a.custid &amp;lt;&amp;gt; b.custid and a.CustName =  b.CustName
and a.CustCity = b.CustCity  and a.Passport_Number =  b.Passport_Number

&lt;img alt=&quot;selfjoin-showing-duplicate-rows&quot; border=&quot;0&quot; height=&quot;122&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg10cOBjvKJeJYNPkxFDT27MnRTUuJcXQlkJsi7j7-gLHl6rlQB0V4fEn9wyosk053L8SuU44-x6qfnPoNt9zRKCtmXt2ihr-ANXHWlD_gOE1i3C1bHBtzlar-0PUJh9NwN7vLW3joI5MQS/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;selfjoin-showing-duplicate-rows&quot; width=&quot;300&quot; /&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Now we have realized that custid 1, 4 &amp;amp; 5 are duplicate. The self-join statement accompanied by delete statement will give us the desired output of keeping the last duplicate record by eliminating all the previous duplicate records. We will use the &lt;b&gt;&lt;u&gt;Common Table Expression (CTE)&lt;/u&gt;&lt;/b&gt; and put the Self Join query in it.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;With Duplicates as
(select distinct a.custid as Customer_ID
from customers2 a join customers2 b
on a.custid &amp;lt;&amp;gt; b.custid and a.CustName =  b.CustName
and a.CustCity = b.CustCity  and a.Passport_Number =  b.Passport_Number
) 
Delete from Customers2
where custid in (select Customer_ID from Duplicates)
and custid &amp;lt;&amp;gt; (select max(Customer_ID) from Duplicates)&lt;/pre&gt;
Let’s check which rows got deleted.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers2
go

&lt;img alt=&quot;keeping-last-record&quot; border=&quot;0&quot; height=&quot;144&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjylbFpVSqTvO0C1JoF4VvdLSqLlsq7pLxQBf0LjcEP4O0uFJjsa2zFP9rgl0-Uljz4gLx5PluUhY1sxk-dLiQ3oXh0Sx4GPpK0MXvLPCh3Z7mQVvIPWlBUtblfVP25ba0ur4Ywj-E1nEiN/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;keeping-last-record&quot; width=&quot;322&quot; /&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;b&gt;
&lt;/b&gt;&lt;/pre&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;b&gt;
Scenario 2.b: Delete all duplicate records but keep the first original one&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Let’s first truncate the customers2 table and add the same rows again.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Truncate Table customers2
go
Insert into customers2 Values(1, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
Insert into customers2 Values(2, &#39;Martin&#39;, &#39;London&#39;, &#39;L873X92&#39;)
Insert into customers2 Values(3, &#39;Smith&#39;, &#39;New York&#39;, &#39;N293Y99&#39;)
Insert into customers2 Values(4, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
Insert into customers2 Values(5, &#39;John&#39;, &#39;Paris&#39;, &#39;P123X78&#39;)
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
The only change in the sub query will be that we need to use min(CustomerID) instead of max(CustomerID).&lt;br /&gt;
&lt;br /&gt;
So the query will be as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;With Duplicates as
(select distinct a.custid as Customer_ID
from customers2 a join customers2 b
on a.custid &amp;lt;&amp;gt; b.custid and a.CustName =  b.CustName
and a.CustCity = b.CustCity  and a.Passport_Number =  b.Passport_Number
) 
Delete from Customers2
where custid in (select Customer_ID from Duplicates)
and custid &amp;lt;&amp;gt; (select min(Customer_ID) from Duplicates)&lt;/pre&gt;
Let us confirm this in the customers2 table.&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers2
go

&lt;img alt=&quot;keeping-first-record&quot; border=&quot;0&quot; height=&quot;157&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiU47zIudjrmdPKmaSOmizq7pvKZj3zTd61VZ22jq-8MnjCLpK01tcxeIVtU42Ws7vMiPfsp3b_HzSRsdBVp_gGg0qFLqmzKGSA9pSVDP9ATK3dJ1TZMvqrAthevksOL-tcz71Y8F9zg0-k/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;keeping-first-record&quot; width=&quot;308&quot; /&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
And that’s how we can delete duplicate records in SQL Server with tables without primary key, containing primary key and by keeping one original row.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/07/sql-server-delete-duplicate-rows_25.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWwnfmtGIDdWd8SrMSNk7p-d0SUykT0JJd2Qqqhi-_50pUBYTJbaPA7UXrfqnIJA6TTvvbKfeVmFku02VZnqX8Z_wAVzmREu1upM0tOgsd-zbJzXe0tNyrPS8Mf0-0Uc9TZXSVgCoXVSVY/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-4285000257541837946</guid><pubDate>Mon, 18 Jul 2016 02:57:00 +0000</pubDate><atom:updated>2016-07-17T19:57:53.400-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>T-SQL Insert Into Table Examples</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In T-SQL, to add records into a table (SQL Server) we use a Data Manipulation Language (DML) command known as &lt;strong&gt;Insert statement&lt;/strong&gt;. In this article, we are going to explore the different capabilities of the T-SQL Insert statement.&lt;br /&gt;
&lt;br /&gt;
Let us create a table &lt;em&gt;Table1&lt;/em&gt; with 3 columns A, B and C&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table1
(A int,
 B Varchar(10),
 C Date)&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 1: Add one complete row, date in American format&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Here we will mention the actual column values in the &lt;em&gt;Values&lt;/em&gt; clause in a sequence that matches the columns mentioned in the CREATE TABLE statement.&lt;br /&gt;
&lt;br /&gt;
Syntax: Insert into Table_Name Values(Col1 Value, Col2 Value….., Coln Value)&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table1 Values (1,&#39;Aa&#39;, &#39;12/13/2014&#39;)&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 2: Add one complete row, date in British format&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
The date can be entered either in American or British format.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table1 Values (2,&#39;Bb&#39;, &#39;13-Dec-2014&#39;)&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 3: Add one partial row, specifying Null&lt;/strong&gt;&lt;br /&gt;
Sometimes we do not want to add values in every column. Let us create a new row by specifying values for A and C columns only. 
  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table1 Values (3, Null, &#39;14-Dec-2014&#39;) &lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 4: Add one partial row, specifying column names&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Consider there are 25 columns in a SQL table, and we want to create a new row by specifying values for only 3 columns. In that case, mentioning Null for the remaining 22 columns multiple times will be cumbersome. So instead of that, we can only mention those 3 columns after the table name, and mention the values for only those 3 columns. The remaining 22 columns by default will get null values. Caution: There should not be primary key or NOT NULL constraint to any of those columns.&lt;br /&gt;
&lt;br /&gt;
Syntax: Insert into Table_Name (Column1, Column3, Column5) Values(Col1 Value, Col3 Value, Col5 Value)&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table1(A,C) Values (4,&#39;15-Dec-2014&#39;)&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Note:&lt;/strong&gt; The columns can be mentioned in any sequence after the table name, but then the values need to mentioned in the same sequence.&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 5: Ignore the identity column while adding row.&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
If the table has identity (auto number generation property) column, then by default we cannot add value to that column.&lt;br /&gt;
&lt;br /&gt;
Let us create table Table2 with A as identity column and B, C as integer data type columns&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table2
(A int identity,
 B int,
 C int)&lt;/pre&gt;
&lt;br /&gt;
To add a record, use the syntax demoed in Example 4.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table2 (B,C) Values(100,200)&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 6: Ignore the computed column while adding row&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us create table Table3 with a,b and c as 3 columns. C will be the computed column.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table3
(A int,
 B int,
 C as (a + b))&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table3 Values(200, 300)&lt;/pre&gt;
&lt;br /&gt;
The column C will implicitly get value 500!&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Example 7: Bulk Insertion – Select along with Union All&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
If we want to add many records in a table through one statement, then SELECT statement can be associated with INSERT statement instead of &lt;em&gt;values&lt;/em&gt; clause.&lt;br /&gt;
&lt;br /&gt;
Let us create table Table4 first.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table4
(a int, b varchar(10)
)&lt;/pre&gt;
&lt;br /&gt;
Now if we want add five rows in Table4, we will use SELECT statement along with UNION ALL.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table4
Select 1,&#39;A&#39;
Union All
Select 2,&#39;B&#39;
Union All
Select 3,&#39;C&#39;
Union All
Select 4,&#39;D&#39;
Union All
Select 5,&#39;E&#39;&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 8: Bulk Insertion – Select along with Union All, violation of constraint&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
If any record violates the constraint, then the entire set gets rejected.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table5
(a int check (a &amp;lt;= 3), b varchar(10)
)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table5
Select 1,&#39;A&#39;
Union All
Select 2,&#39;B&#39;
Union All
Select 3,&#39;C&#39;
Union All
Select 4,&#39;D&#39;
Union All
Select 5,&#39;E&#39;&lt;/pre&gt;
&lt;br /&gt;
No rows will get added in Table 5.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Example 9: Bulk Insertion – Multiple rows through Values clause itself&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
From SQL Server 2008 version onwards, the Values clause has been strengthen to add multiple rows. &lt;br /&gt;
&lt;br /&gt;
Syntax:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert Into TableName
Values    (……………..),
           (……………..),
           (……………..),
           (……………..)&lt;/pre&gt;
&lt;br /&gt;
So in the Table4 now, we will add three records using the Values clause.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table4
Values (6,&#39;E&#39;),(7,&#39;F&#39;),(8,&#39;G&#39;)&lt;/pre&gt;
&lt;br /&gt;
Note: If any one record fails then the entire batch gets rejected.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Example 10: Bulk Insertion – Copying records of another table&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Many a times we need to copy records from one table to another.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Target_Table
Select * from Source_Table&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Note:&lt;/strong&gt; Here it is assumed that the structure of source &amp;amp; target tables are same. That means the number of columns should be same, and positional columns should be compatible as per data type &amp;amp; size.&lt;br /&gt;
Let us create table Table6 similar to Table4&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table6
(a int, b varchar(10)
)&lt;/pre&gt;
&lt;br /&gt;
Now all records of Table4 need to be inserted in Table6.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table6
Select * from Table4&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;strong&gt;Example 11: Bulk Insertion – Copying records of another table, but not in all columns.&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Let us create table Table7 similar to Table4&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table Table7
(a int, b varchar(10)
)&lt;/pre&gt;
&lt;br /&gt;
Here we need to mention the column names. Suppose we want to add records, but taking values of column B only, then the command will be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Insert into Table7(B)
Select B from Table4&lt;/pre&gt;
&lt;h3&gt;
Conclusion: &lt;/h3&gt;
&lt;br /&gt;
In this article we have seen how to &lt;strong&gt;add records into an SQL Server table using the T-SQL Insert statement&lt;/strong&gt; with its multiple examples.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/07/t-sql-insert-into-table-examples_17.html</link><author>noreply@blogger.com (Mandar Mulay)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-4994000527497878345</guid><pubDate>Mon, 27 Jun 2016 14:17:00 +0000</pubDate><atom:updated>2016-06-27T07:17:33.334-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server Alter Table with Add Column</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
There are many scenarios where we need to do structural changes to a table, i.e. adding a column, modifying data type, dropping a column and so on. This change to an existing table is possible by issuing a SQL Server Data Definition Language (DDL) T-SQL command known as &lt;strong&gt;Alter Table&lt;/strong&gt;. &lt;br /&gt;
&lt;br /&gt;
In this article we are specifically focusing on adding a new column in a table using SQL Server Alter Table.&lt;br /&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;
Scenario 1: Adding columns to empty table&lt;/h2&gt;
When the table is created and if there are no records in that table, then there is no problem in adding a column or multiple columns to that table.&lt;br /&gt;
&lt;br /&gt;
Let us see the following example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table customers1
(
  custid varchar(5),
 custname varchar(50)
)
go&lt;/pre&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;Scenario 1.a: Adding single column:&lt;/span&gt;&lt;/h3&gt;
After creating the table, we realize that date of birth (DOB) column needs to be added. The following command will help us in achieving this.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers1
Add DOB Date
go&lt;/pre&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;Scenario 1.b: Adding multiple columns:&lt;/span&gt;&lt;/h3&gt;
Adding two more columns is also very easy. Let us add &lt;em&gt;nationality&lt;/em&gt; and &lt;em&gt;gender&lt;/em&gt; as two more columns by just having a comma separator in each definition.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers1
Add Nationality Varchar(40), Gender Char(1)
go&lt;/pre&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;Scenario 1.c: Adding columns with constraints:&lt;/span&gt;&lt;/h3&gt;
Adding a column with constraint such as primary key, unique key, foreign key, not null, check or default is again not challenging in an empty table. &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Note&lt;/strong&gt; – A primary key constraint cannot be added on the new column if there is already a primary key on any other existing column.&lt;br /&gt;
&lt;br /&gt;
Let us add &lt;em&gt;SSN&lt;/em&gt; and &lt;em&gt;deposit amount&lt;/em&gt; as two columns, SSN having primary key and deposit amount having check constraint.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers1
Add SSN Varchar(10) Primary Key, 
Deposit_Amount Integer Check(Deposit_Amount &amp;gt;= 200)
go&lt;/pre&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;
Scenario 2: Adding columns to table having records&lt;/h2&gt;
When a column is added to a table with existing records, then for those records, by default a null value is assigned by SQL Server.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Adding column on table having existing records.&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Let us create table customers2 and add 2 records in it.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table customers2
(custid varchar(5),
 custname varchar(50)
 )
 Go
Insert into customers2 Values(&#39;C1&#39;,&#39;John&#39;)
Insert into customers2 Values(&#39;C2&#39;,&#39;Martin&#39;)
go&lt;/pre&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;Scenario 2.a: Adding columns with default null values on existing records.&lt;/span&gt;&lt;/h4&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers2
Add DOB Date
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Let us see the table Customers2&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers2&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sqlserver-nulls-new-column&quot; border=&quot;0&quot; height=&quot;116&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhThKXooWUTCjG8gKXfW024P7tXGzwx104CC1qtxao64ONf7gbaxK177V3C5hwQ8i3IloL9ibcpP43iWdbxRh7J5ilFe1ss0OAvWjGDNtUYl33dVrb6BwjiWZ784wqa-54-O7EHZHDws4Fi/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sqlserver-nulls-new-column&quot; width=&quot;194&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image2-No-Default-Value&lt;/i&gt;&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;Scenario 2.b: Adding columns with default value &lt;/span&gt;&lt;/h3&gt;
It might happen that you want to add a column specifying some default value and there are existing records in the table. &lt;u&gt;But in the default setup, those existing records will not get that value.&lt;/u&gt;&lt;br /&gt;
Let us add &lt;em&gt;token&lt;/em&gt; amount as a column to this Customers2 table with default value as 100.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers2
Add Token_Amount Integer Default 100
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Let us see the table Customers2&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers2&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-no-default-value&quot; border=&quot;0&quot; height=&quot;126&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKBVal0-aGr3vOe0tz39hjUiNDtIIL17R1bfTe6TRpSOr6feyPaZE4Qi5EUlegOcIor7DYo5qF94pOzhJHB59CJgxWc9k2HnQLn8zQgeRPY743ot3AFyD3DNDA9V7IhL50AgYjV1E5QnNU/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-no-default-value&quot; width=&quot;288&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image2-No-Default-Value&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Note -The default value will be effective when new record is added.&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;
Scenario 2.c: Adding columns with default value and applying those values on existing records.&lt;/span&gt;&lt;/h3&gt;
Let us add another column tax with default value as 50. This value needs to be added to the existing records as well. We need to explicitly specify the clause &lt;u&gt;With Values.&lt;/u&gt;&lt;br /&gt;
&lt;u&gt;&lt;br /&gt;&lt;/u&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers2
Add Tax Integer Default 50 With Values
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;default-value-withclause&quot; border=&quot;0&quot; height=&quot;121&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSXkgq8-tEDcLl2LxszQ8_I1Kk1dmB5mWtvRSU3G7OYXnFrJihJbgBbxi4CkIUdKe1L8U3cXkkTNWnN2pKbhPq8muz_T44ONg9I-Li-9Os9LPBzT9fHAmI1n9VJ7LPuYd3MpmPzie6xL3z/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;default-value-withclause&quot; width=&quot;325&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image3-Default-Value-WithClause&lt;/i&gt;&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;
Scenario 2.d: Adding columns with Not Null constraint on existing records.&lt;/span&gt;&lt;/h3&gt;
Let us add a column &lt;em&gt;Country&lt;/em&gt; with Not Null constraint. Now this will be contradictory because the earlier two records cannot have null value for Country.&lt;br /&gt;
&lt;br /&gt;
Let us try.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers2
Add Country Varchar(50) Not Null
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
It will throw the following error.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: red;&quot;&gt;ALTER TABLE only allows columns to be added that can contain nulls&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: red;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
To rectify this, we need to mention the default value which will safeguard the earlier records.&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-size: small;&quot;&gt;
Scenario 2.e: Adding columns with not null constraint and default value on existing records&lt;/span&gt;&lt;/h3&gt;
Let’s have &lt;em&gt;India&lt;/em&gt; as the default value.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Alter Table customers2
Add Country Varchar(50) Default &#39;India&#39; Not Null
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Now this works fine. Let us see the table again.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select * from customers2&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;default-value-notnull&quot; border=&quot;0&quot; height=&quot;122&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin225lOe7w80H9FQqNBYc0_735-0onJwCFx0Iyilved-5Mvw_idvc-zHpl-UjtlfU4kh__cA6QUq7fmwNY7miqVqVyARS0pvDh-dCW3qPEDMWKcubw4cq_dD8O6SSjkldT2O1YiEg39ykv/?imgmax=800&quot; style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;default-value-notnull&quot; width=&quot;375&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image4-Default-Value-NotNull&lt;/i&gt;&lt;br /&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/h4&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
Conclusion:&lt;/h4&gt;
In this article, we have seen the following scenarios of &lt;strong&gt;using ALTER table to add column to a SQL Server table&lt;/strong&gt;:&lt;br /&gt;
&lt;br /&gt;
1. Adding one or multiple columns to an empty table.&lt;br /&gt;
2. Adding column to table having records. Those records get default value as null.&lt;br /&gt;
3. Adding column with default value to table having records&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;In absence of With Values clause &lt;/li&gt;
&lt;li&gt;In presence of With Values clause&lt;/li&gt;
&lt;/ul&gt;
4. Adding column with not null constraint to table having records&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;In absence of Default clause &lt;/li&gt;
&lt;li&gt;In presence of Default clause&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/06/sql-server-alter-table-with-add-column_27.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhThKXooWUTCjG8gKXfW024P7tXGzwx104CC1qtxao64ONf7gbaxK177V3C5hwQ8i3IloL9ibcpP43iWdbxRh7J5ilFe1ss0OAvWjGDNtUYl33dVrb6BwjiWZ784wqa-54-O7EHZHDws4Fi/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-2379130694254020478</guid><pubDate>Thu, 02 Jun 2016 06:21:00 +0000</pubDate><atom:updated>2016-06-01T23:23:26.641-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>T-SQL Date Format with Convert</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In this article we are going to see a very handy &lt;strong&gt;SQL Server T-SQL function for formatting date called Convert()&lt;/strong&gt;. It is generally used to show date values in different styles or formats.&lt;br /&gt;
&lt;br /&gt;
Normally any date value when entered in a SQL Server table gets displayed in the default format as YYYY-MM-DD. Many a times, in your client application you may need to change the output of date &amp;amp; time for display purpose. &lt;u&gt;For doing this the T-SQL Convert function is used.&lt;/u&gt;&lt;br /&gt;
&lt;u&gt;&lt;br /&gt;&lt;/u&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Convert Function Example&lt;/span&gt;&lt;/h3&gt;
Let us create a sample database Convert_Demo in our SQL Server database instance.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Use Master
go
Create Database Convert_Demo
go
Use Convert_Demo
go
CREATE TABLE EMP
       (EMPNO Integer Primary Key,
        ENAME Varchar(15),
        JOB Varchar(9),
        MGR Integer,
        HIREDATE date,
        SAL Integer,
        COMM Integer,
        DEPTNO Integer);
go
INSERT INTO EMP VALUES
        (7369, &#39;SMITH&#39;,  &#39;CLERK&#39;,     7902, &#39;12/17/80&#39;,
        800, NULL, 20);
INSERT INTO EMP VALUES
        (7499, &#39;ALLEN&#39;,  &#39;SALESMAN&#39;,  7698,
        &#39;5/20/81&#39;,1600,  300, 30);
INSERT INTO EMP VALUES
        (7521, &#39;WARD&#39;,   &#39;SALESMAN&#39;,  7698,
        &#39;5/22/81&#39;, 1250,  500, 30);
INSERT INTO EMP VALUES
        (7566, &#39;JONES&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;4/2/81&#39;,  2975, NULL, 20);
INSERT INTO EMP VALUES
        (7654, &#39;MARTIN&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/28/81&#39;, 1250, 1400, 30);
INSERT INTO EMP VALUES
        (7698, &#39;BLAKE&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;5/1/81&#39;,  2850, NULL, 30);
INSERT INTO EMP VALUES
        (7782, &#39;CLARK&#39;,  &#39;MANAGER&#39;,   7839,
        &#39;6/9/81&#39;,  2450, NULL, 10);
INSERT INTO EMP VALUES
        (7788, &#39;SCOTT&#39;,  &#39;ANALYST&#39;,   7566,
        &#39;12/9/82&#39;, 3000, NULL, 20);
INSERT INTO EMP VALUES
        (7839, &#39;KING&#39;,   &#39;PRESIDENT&#39;, NULL,
        &#39;11/17/81&#39;, 5000, NULL, 10);
INSERT INTO EMP VALUES
        (7844, &#39;TURNER&#39;, &#39;SALESMAN&#39;,  7698,
        &#39;9/8/1981&#39;,  1500,    0, 30);
INSERT INTO EMP VALUES
        (7876, &#39;ADAMS&#39;,  &#39;CLERK&#39;,     7788,
        &#39;1/12/83&#39;, 1100, NULL, 20);
INSERT INTO EMP VALUES
        (7900, &#39;JAMES&#39;,  &#39;CLERK&#39;,     7698,
        &#39;12/3/81&#39;,   950, NULL, 30);
INSERT INTO EMP VALUES
        (7902, &#39;FORD&#39;,   &#39;ANALYST&#39;,   7566,
        &#39;12/3/81&#39;,  3000, NULL, 20);
INSERT INTO EMP VALUES
        (7934, &#39;MILLER&#39;, &#39;CLERK&#39;,     7782,
        &#39;1/23/82&#39;, 1300, NULL, 10);
go&lt;/pre&gt;
&lt;br /&gt;
Now let us see the default presentation style of the &lt;em&gt;hiredate&lt;/em&gt; column by executing the following SQL statement.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, hiredate from emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-default-date-format&quot; border=&quot;0&quot; height=&quot;331&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimpiyEq118jZfNYgW8wDTEhxdnYnNxenrSjimi8XbKhuCaLB8o1D-taKFDpTS2qtaCgy777_wpvr1VzXXyrtaio9HAIURW9ttmK8qWO47H9poEdihKhjpEksW4P_ebMu7YtdPlr55rrEb4/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-default-date-format&quot; width=&quot;380&quot; /&gt;

&lt;br /&gt;
&lt;i&gt;Image1-Default-date-format&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Syntax of Convert function&lt;/span&gt;&lt;/h3&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;CONVERT(data_type(length),data_to_be_converted,style)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;strong&gt;Data_type(length)&lt;/strong&gt; - varchar data type particulary for displaying dates in different format.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;data_to_be_converted&lt;/strong&gt; - The date value which needs to be converted.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Style&lt;/strong&gt; - There are some predefined style ids like 101 for American date format, 103 in British format and so on. The style chart has been shown next –&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;sql-date-formats&quot; border=&quot;0&quot; height=&quot;558&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIZ6mFcp9XMRlK3CVK9ONIt-pAKnO1too03M0TNbIslzEtSlBuR67Kn2UfpoYIxpztIXft2PctgsnrBWffvx9Z3o4ipD9JiLT2fJ_3TPa5-b0b1eCKzEq39SdtnU0e2ojkVSpjcLyMHb3I/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-date-formats&quot; width=&quot;380&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Now let us see the employee names &amp;amp; hiredate in American as well as British formats using T-SQL Convert function.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, hiredate as [Default Date Format],
convert(varchar, hiredate, 101) as [American],
convert(varchar, hiredate, 103) as [British] 
from emp

&lt;img alt=&quot;sql-changed-date-formats&quot; border=&quot;0&quot; height=&quot;351&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt5Iv1j02yTPWyA4MIP11RPMHmGBns2KIhY01yMprXGzRIE3v4swSspAtyyxvXBAAR1oGciumD51W7mxVTM2oSlCHbAu1BN5bvDsmWeUqEfrxaje1rDct4LdB-wXdHespBht5SYGPfhSCs/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-changed-date-formats&quot; width=&quot;399&quot; /&gt;&lt;/pre&gt;
&lt;i&gt;Image2-Changed-Date-Formats&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Convert without StyleID:&lt;/span&gt;&lt;/h3&gt;
Convert is also useful to &lt;strong&gt;convert from one data type to another&lt;/strong&gt; – For example changing Float to Int, Number to Float or Number to Varchar.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Using Convert to change from Float to Int&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT CONVERT(int, 14.85)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-changing-float-to-int&quot; border=&quot;0&quot; height=&quot;120&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRruceo30AAQKdbHCkAyH_We9g5hqQW8du1ZxgL6hwk_OA6r5Sw3WyFi9C8OF9h0fmX_TrbWjQcj5B-9e6VM4W35XoZJrUvBI_G4pu7G56zmFa5hGjqOwTTdQ5ZBzqjeb7Tot4duNbBwZL/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-changing-float-to-int&quot; width=&quot;176&quot; /&gt;

&lt;br /&gt;
&lt;i&gt;Image3-Changing-Float-To-Int&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt; &lt;strong&gt;Using Convert to change from Number to Float&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT CONVERT(float, 14.0989654)    &lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-number-to-float&quot; border=&quot;0&quot; height=&quot;81&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjITvYLor1r4CYex9YG2FMX7TgKNtCnLArWKrnhcTcDFuiwPPXsH3v23EoNDrVOAHCLOuXVZtxBiFVs4QugNe7T3d05AWQ3fdIyggWOhvdRM4jGmw4B7xX6fIR8FjjJ19jBnbBPIbcLwro_/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-number-to-float&quot; width=&quot;166&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image4-Number-to-Float&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt; &lt;b&gt;Using Convert to change from Number to Varchar&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT CONVERT(varchar(4), &#39;12.3456&#39;)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;sql-number-to-varchar&quot; border=&quot;0&quot; height=&quot;82&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjx03GS-uHFPNlwtVz_HYo518eZ7if5xcNNa4WTNypqBouUhlqAOqBVAqRmEVSWQb7LXMsbTWT1s32LKtsKuD3DUxuvzBTX6tBint5HlM6jMvUXZuNZtRAAumLTtGWHOn_M1GF0xFY09q5Z/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sql-number-to-varchar&quot; width=&quot;175&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image5-Number-to-Varchar&lt;/i&gt;&lt;br /&gt;
&lt;em&gt;&lt;/em&gt;&lt;br /&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
Conclusion:&lt;/h4&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&amp;nbsp;&lt;/div&gt;
We have seen in this article that using &lt;strong&gt;T-SQL function Convert&lt;/strong&gt;, we can display date in different formats and also can type cast one data type into another.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/06/t-sql-date-format-with-convert.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimpiyEq118jZfNYgW8wDTEhxdnYnNxenrSjimi8XbKhuCaLB8o1D-taKFDpTS2qtaCgy777_wpvr1VzXXyrtaio9HAIURW9ttmK8qWO47H9poEdihKhjpEksW4P_ebMu7YtdPlr55rrEb4/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-3143422852714132666</guid><pubDate>Sat, 23 Apr 2016 06:28:00 +0000</pubDate><atom:updated>2016-05-15T20:10:53.186-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server CASE Statement and CASE WHEN Examples</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Many a times there’s a need to create a derived column in an output, based on some condition. The condition is similar to the typical &lt;strong&gt;if&lt;/strong&gt; construct we use if many programming languages. &lt;br /&gt;
&lt;br /&gt;
In SQL scripting, we can use &lt;strong&gt;Case expressions or Case Statements &lt;/strong&gt;as you may call them,&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;to create a derived column based on a condition. &lt;br /&gt;
&lt;br /&gt;
Also read about &lt;a href=&quot;http://www.sqlservercurry.com/2016/05/nested-case-statement-in-sql-server_15.html&quot; target=&quot;_blank&quot;&gt;Nested Case Statements in SQL Server&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Let us first execute a sample database creation script that we will be using in our examples:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Use Master
go
Create Database Case_Demo
go
Use Case_Demo
go
CREATE TABLE EMP
       (EMPNO Integer,
        ENAME Varchar(15),
        JOB Varchar(9),
        MGR Integer,
        HIREDATE datetime,
        SAL Integer,
        COMM Integer,
        DEPTNO Integer)
go
INSERT INTO EMP VALUES
        (7369, &#39;SMITH&#39;, &#39;CLERK&#39;, 7902, &#39;12/17/80&#39;, 800, NULL, 20)
INSERT INTO EMP VALUES
        (7499, &#39;ALLEN&#39;, &#39;SALESMAN&#39;, 7698, &#39;5/20/81&#39;, 1600, 300, 30)
INSERT INTO EMP VALUES
        (7521, &#39;WARD&#39;, &#39;SALESMAN&#39;, 7698, &#39;5/22/81&#39;, 1250, 500, 30)
INSERT INTO EMP VALUES
        (7566, &#39;JONES&#39;, &#39;MANAGER&#39;,   7839, &#39;4/2/81&#39;, 2975, NULL, 20)
INSERT INTO EMP VALUES
        (7654, &#39;MARTIN&#39;, &#39;SALESMAN&#39;, 7698, &#39;9/28/81&#39;, 1250, 1400, 30)
INSERT INTO EMP VALUES
        (7698, &#39;BLAKE&#39;, &#39;MANAGER&#39;,   7839, &#39;5/1/81&#39;, 2850, NULL, 30)
INSERT INTO EMP VALUES
        (7782, &#39;CLARK&#39;, &#39;MANAGER&#39;,   7839, &#39;6/9/81&#39;, 2450, NULL, 10)
INSERT INTO EMP VALUES
        (7788, &#39;SCOTT&#39;,  &#39;ANALYST&#39;,  7566, &#39;12/9/82&#39;, 3000, NULL, 20)
INSERT INTO EMP VALUES
        (7839, &#39;KING&#39;,   &#39;PRESIDENT&#39;, NULL, &#39;11/17/81&#39;, 5000, NULL, 10)
INSERT INTO EMP VALUES
        (7844, &#39;TURNER&#39;, &#39;SALESMAN&#39;, 7698, &#39;9/8/1981&#39;,1500,    0, 30)
INSERT INTO EMP VALUES
        (7876, &#39;ADAMS&#39;, &#39;CLERK&#39;, 7788, &#39;1/12/83&#39;, 1100, NULL, 20)
INSERT INTO EMP VALUES
        (7900, &#39;JAMES&#39;, &#39;CLERK&#39;, 7698,  &#39;12/3/81&#39;, 950, NULL, 30)
INSERT INTO EMP VALUES
        (7902, &#39;FORD&#39;,   &#39;ANALYST&#39;, 7566, &#39;12/3/81&#39;, 3000, NULL, 20)
INSERT INTO EMP VALUES
        (7934, &#39;MILLER&#39;, &#39;CLERK&#39;,  7782, &#39;1/23/82&#39;, 1300, NULL, 10)
go&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
There are two types of Case expressions:&lt;br /&gt;
&lt;br /&gt;
1. Case acting as a &lt;b&gt;Switch Case&lt;/b&gt; construct.&lt;br /&gt;
2. Case acting like an &lt;b&gt;If…Else If….Else&lt;/b&gt; construct.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;Switch Case Construct&lt;/span&gt;&lt;/h3&gt;
Let us see an example of Case acting as a &lt;b&gt;Switch Case construct&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
The syntax is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Case Expression or Column Name
    When Value1 Then Statement1 or Expression 1
    When Value2 Then Statement2 or Expression 2
    When Value3 Then Statement3 or Expression 3
    .......................................................
    .......................................................
    When Value m Then Statement m or Expression m    
    Else
        Statement n or Expression n
End&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;strong&gt;Note:&lt;/strong&gt; The &lt;em&gt;Value&lt;/em&gt; above will be the actual value from a column, i.e. string or numeric or date value.&lt;br /&gt;
&lt;br /&gt;
The &lt;em&gt;Statement&lt;/em&gt; can be a string , numeric or date value. &lt;em&gt;Expression&lt;/em&gt; can be either a derived value such as &lt;i&gt;[Column Name] * 12&lt;/i&gt; or using a T-SQL function &lt;i&gt;Lower([Column Name])&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Let us see an example to make things clearer.&lt;br /&gt;
&lt;br /&gt;
Let us display the employee name, job and &lt;b&gt;job_points&lt;/b&gt; for each record. Now job_points will be a derived column based on a condition that says - If job is of Analyst then job_points will be 100, if it is clerk then 200, else for any other job type it will be 300.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job,  case job    
    when &#39;Analyst&#39; then 100
    when &#39;Clerk&#39; then 200
    else 300
         end as &quot;Job Points&quot;
from emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;1-case-as-switch-case&quot; border=&quot;0&quot; height=&quot;370&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-bav1Rhd4zGLlMKRk7n0Mj7o9IFPZlfgheUwbj5JypPhck12qQiYpUYpuqH8VDI5AyhVpW6VFY4W2bH2o3o0ZEuwed5LCWPFTq3ZfyjqvzpATBYXQQsDHrTRR1YLuhSQWZ-ni3C2NBhzA/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;1-case-as-switch-case&quot; width=&quot;306&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 1: Case-As-Switch-Case&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;i&gt;&lt;/i&gt;&lt;br /&gt;
&lt;em&gt;Else&lt;/em&gt; part is optional. If it is not mentioned, then NULL will be returned for the default values.&lt;br /&gt;
Let us see the same&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job, case job    
    when &#39;Analyst&#39; then 100
    when &#39;Clerk&#39; then 200
    end as &quot;Job Points&quot;
from emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;2-case-without else&quot; border=&quot;0&quot; height=&quot;342&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNVQigUFODxcKyV9lT3EHFb3WaBkDqqpT2Tv8GUWiJqesrtgKgw9n9EEcYl2jWHCPlfzeRx0QdWzWXuhxitZQKtcfNzDd0GiQGOqkjPii1Ro-EQpjyqjm8iGDMX21cDX5y1falN4jz5WI-/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;2-case-without else&quot; width=&quot;300&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 2: Case-Without Else&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
All the statements mentioned in the &lt;em&gt;then&lt;/em&gt; clause should be of the same data type.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job, case job    
    when &#39;Analyst&#39; then 100
    when &#39;Clerk&#39; then &#39;Two Hundred&#39;
    end as &quot;Job Points&quot;
from emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
The above query throws an error since at first the &lt;em&gt;when&lt;/em&gt; clause is 100 i.e. a numeric value, but the next &lt;em&gt;when&lt;/em&gt; clause has &#39;Two Hundred&#39; as a value of string type.&lt;br /&gt;
&lt;br /&gt;
The error message is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Msg 245, Level 16, State 1, Line 1 &lt;/b&gt;&lt;b&gt;Conversion failed when converting the varchar value &#39;Two Hundred&#39; to data type int.&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
As I mentioned earlier, &lt;em&gt;All the statements mentioned in the then clause should be of the same data type. &lt;/em&gt;So to fix this error, we need to enclose 100 in single quotes to make it a Varchar value.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job, case job    
    when &#39;Analyst&#39; then &#39;100&#39;
    when &#39;Clerk&#39; then &#39;Two Hundred&#39;
    end as &quot;Job Points&quot;
from emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
Now we will get the desired output -&lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;3-case-after-rectification&quot; border=&quot;0&quot; height=&quot;332&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgM1h3J3UnkxCHoCNFY5_JkM1KThRE5o6SLiRfsttM2CjRhJJLvp8sn1mXrT111M67ErRuBiZgY2H1kfINoH-eNEvcnX_rk9H55c3sA5gx0POTuMHsX5XijjDJBMwAo7MmIbZYNKpsKGzEg/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;3-case-after-rectification&quot; width=&quot;342&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 3: Case-After-Rectification&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;IF ELSE Construct&lt;/span&gt;&lt;/h3&gt;
&lt;div&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
Let us now see how to use the Case expression as an &lt;b&gt;If…Else If….Else&lt;/b&gt; construct.&lt;br /&gt;
The syntax will be as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Case 
    When Boolean Condition 1 Then Statement1 or Expression 1
    When Boolean Condition 2 Then Statement2 or Expression 2
    When Boolean Condition 3 Then Statement3 or Expression 3
    ........................................................
    ........................................................
    When Boolean Condition m Then Statement m    or Expression m
    Else
        Statement n or Expression n
End&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;strong&gt;Note:&lt;/strong&gt; &lt;u&gt;In this syntax, after the CASE keyword there is no Expression or Column Name&lt;/u&gt;. We directly have a When clause. The When clause will have a Boolean condition in which the column name or expression will be included.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of this.&lt;br /&gt;
&lt;br /&gt;
Let us create a query which will show employee name, salary and &lt;b&gt;salary class&lt;/b&gt;. If the salary is greater than or equal to 5000 then salary class will be A, if it is between 2500 and 4999 then it will be B and for remaining salaries, values will be C.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, sal, case 
    when sal &amp;gt;= 5000 then &#39;A&#39;
    when sal &amp;gt;= 2500 then &#39;B&#39;
    else
    &#39;C&#39;
           end as &quot;Salary Class&quot;
From Emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;4-case-if-else&quot; border=&quot;0&quot; height=&quot;350&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijoLtQA-A04owGvO3NhV8tLl3lIZycZss00bxgZm_ARoQVjmAHJV2N1VS8gvptFZ_bInrGqjN8nn8YddKVAxdxpM5TmowON0_zUqVs07H-H_F3ZyIilfSoMlfdyMXO3lnA4JBXijxssC93/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;4-case-if-else&quot; width=&quot;270&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 4: Case-If-Else&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;strong&gt;Note&lt;/strong&gt;: &lt;u&gt;The sequence of Boolean conditions will matter a lot.&lt;/u&gt; Whichever condition is true, its statement or expression gets executed and it comes out of the CASE expression for that record.&lt;br /&gt;
&lt;br /&gt;
So if we swap the first two conditions in the above example, the output will go haywire.&lt;br /&gt;
&lt;br /&gt;
Let us see an example&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, sal, case 
    when sal &amp;gt;= 3000 then &#39;B&#39;
    when sal &amp;gt;= 5000 then &#39;A&#39;
    else
    &#39;C&#39;
           end as &quot;Salary Class&quot;
From Emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;5-case-logically-wrong&quot; border=&quot;0&quot; height=&quot;334&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpSPMqVc8UueR40SjTcdTznFcumazkiGy44_bTSMPA2cNHw-gIbZ6CuX6wOCRtdFWz-bD-1FZTGDHLhyphenhyphendv-NqiiJRX-8VfPi8Jwyfo2Mzwuj6cgA9oRO9BM-NnmJoV_K52ALweKUyYeFfK/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;5-case-logically-wrong&quot; width=&quot;266&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 5: Case-Logically-Wrong&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;strong&gt;Note:&lt;/strong&gt; To avoid such logical errors, it will be better to avoid relational operators like &amp;gt;,&amp;gt;=. Instead use the &lt;em&gt;between&lt;/em&gt; operator, mention the exact range and after doing this, if the conditions are given in any sequence, the output will be logically correct. Alternatively if you are going to continue with &amp;gt;,&amp;gt;= operators, then strictly all the conditions should be descending or all should be ascending.&lt;br /&gt;
&lt;br /&gt;
We can mention multiple conditions in each WHEN clause using logical and/or operators.&lt;br /&gt;
&lt;br /&gt;
The following example will depict this point.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select ename, job, sal, case 
    when job = &#39;clerk&#39; and sal &amp;lt; 1000 then &#39;1&#39;
    when job = &#39;clerk&#39; and sal &amp;gt; 1000 then &#39;2&#39;
    when job = &#39;manager&#39; and sal &amp;gt; 2900 then &#39;3&#39;
               end as &quot;Bonus Grade&quot;
From Emp&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;&lt;/pre&gt;
&lt;img alt=&quot;6-case-multiple-conditions-in-when&quot; border=&quot;0&quot; height=&quot;334&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_JCXn7F0tUjkTod4xr6OiObe3cmnZ3AyiYXhcEDPHALJas8T8vI5jHdz-SqfGk_RbzXYzCwDy5t9jd09NBcfpgoZs8hMCIcRtR3Yr_dI3fG-XTd-t3ZI6ld_uBGqCVR3_ZUbZkNrEO__e/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;6-case-multiple-conditions-in-when&quot; width=&quot;404&quot; /&gt;&lt;br /&gt;
&lt;i&gt;Image 6-Case-Multiple-Conditions-In-When&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
We explored the &lt;b&gt;SQL Server CASE statement and also saw the CASE WHEN example&lt;/b&gt;. In the next article, we will explore&amp;nbsp;&lt;a href=&quot;http://www.sqlservercurry.com/2016/05/nested-case-statement-in-sql-server_15.html&quot; target=&quot;_blank&quot;&gt;Nested Case Statements in SQL Server&lt;/a&gt;.&amp;nbsp;and use CASE in Having, Order By and UPDATE statements.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/04/sql-server-case-statement-and-case-when_22.html</link><author>noreply@blogger.com (Mandar Mulay)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-bav1Rhd4zGLlMKRk7n0Mj7o9IFPZlfgheUwbj5JypPhck12qQiYpUYpuqH8VDI5AyhVpW6VFY4W2bH2o3o0ZEuwed5LCWPFTq3ZfyjqvzpATBYXQQsDHrTRR1YLuhSQWZ-ni3C2NBhzA/s72-c?imgmax=800" height="72" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-605499808362743051</guid><pubDate>Wed, 13 Apr 2016 05:40:00 +0000</pubDate><atom:updated>2016-04-12T22:46:21.592-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>PIVOT and UNPIVOT in SQL Server </title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
PIVOT and UNPIVOT are aggregate operators which are available from SQL Server version 2005 onwards.&lt;br /&gt;
&lt;br /&gt;
PIVOT can be used to transform rows into columns while UNPIVOT can be used to transform columns into rows. We will see how to use PIVOT and UNPIVOT in the following examples&lt;br /&gt;
&lt;br /&gt;
Let us create the following table which has sales details of products for each country.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table #sales (country_name varchar(100),product_name varchar(100),&amp;nbsp;
sales_date datetime, sales_amount decimal(12,2))

insert into #sales (country_name,product_name,sales_date,sales_amount)
select &#39;India&#39;,&#39;Television&#39;,&#39;2012-01-10&#39;,35000 union all
select &#39;India&#39;,&#39;Mobile&#39;,&#39;2012-12-19&#39;,22000 union all
select &#39;India&#39;,&#39;Laptop&#39;,&#39;2012-04-11&#39;,62500 union all
select &#39;India&#39;,&#39;Laptop&#39;,&#39;2013-06-23&#39;,45000 union all
select &#39;India&#39;,&#39;Television&#39;,&#39;2012-03-20&#39;,45000 union all
select &#39;India&#39;,&#39;Television&#39;,&#39;2013-05-30&#39;,56000 union all
select &#39;India&#39;,&#39;Mobile&#39;,&#39;2013-02-22&#39;,71200 union all
select &#39;USA&#39;,&#39;Television&#39;,&#39;2012-02-20&#39;,3500 union all
select &#39;USA&#39;,&#39;Mobile&#39;,&#39;2012-11-01&#39;,2700 union all

select &#39;USA&#39;,&#39;Laptop&#39;,&#39;2012-08-19&#39;,6500 union all
select &#39;USA&#39;,&#39;Laptop&#39;,&#39;2013-06-23&#39;,5000 union all
select &#39;USA&#39;,&#39;Television&#39;,&#39;2012-02-12&#39;,4560 union all
select &#39;USA&#39;,&#39;Television&#39;,&#39;2013-06-30&#39;,5100 union all
select &#39;USA&#39;,&#39;Mobile&#39;,&#39;2013-006-06&#39;,2200 &lt;/pre&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;SQL Server PIVOT table Example&lt;/span&gt;&lt;/h3&gt;
Suppose you want to find out the total sales by each product and summarised for each year (ie columns are years). You can use the following code&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT product_name,[2012],[2013] from
(select year(sales_date) as sales_year,product_name,sales_amount FROM #sales)
as t 
PIVOT(SUM(sales_amount) 
      FOR sales_year IN ([2012],[2013])) AS pivot_table&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
&lt;img alt=&quot;pivot-product&quot; border=&quot;0&quot; height=&quot;82&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6z0qpeSZBvTZz7cxqDnFO6Q1qezQJjkTwac7Kv_XvgitJTLNk6KufXlSqH9T8xrEPCbt6k33lnJ1imIIHMZWN7HvV51FU0UptGIa-EtIFlcQkc9bwtiE_XlZyalK-SxcSPaqy5yqYiSFq/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;pivot-product&quot; width=&quot;258&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
If you want to group it by multiple columns, you can simply include that column in the query. For example the following query will do pivot group by country_name and product_name&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;SELECT country_name,product_name,[2012],[2013] from
(select year(sales_date) as sales_year, country_name, product_name,&amp;nbsp;
sales_amount FROM #sales)&amp;nbsp;
as t 
PIVOT(SUM(sales_amount) 
      FOR sales_year IN ([2012],[2013])) AS pivot_table&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
&lt;img alt=&quot;pivot-country-product&quot; border=&quot;0&quot; height=&quot;140&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbqUXd9owBmVgiEJIdAkmBwUwnY95l58ku4f9_4npyKzGSkTj4o3f9W7sy7N9VhbVk7zgMBNukzPasti4EVsFjl3w2XhIouiRxJNwO1IoNCn1lRiDboCQ69weC2IJBAKD0JjLRmqQymqy7/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;pivot-country-product&quot; width=&quot;342&quot; /&gt;&lt;br /&gt;
&lt;h3&gt;
&lt;span style=&quot;font-size: medium;&quot;&gt;SQL Server UnPivot Table Example&lt;/span&gt;&lt;/h3&gt;
To see how unpivot works, let us create the following table&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table #marks(student_name varchar(100), English smallint,&amp;nbsp;
Mathematics smallint,&amp;nbsp;Tamil smallint, Science smallint)&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;insert into #marks(student_name , English, Mathematics, Tamil, Science)
select &#39;Sankar&#39;, 78,91,79,60 union all
select &#39;Nilesh&#39;, 81,90,66,89 union all
select &#39;Murugan&#39;, 94,88,72,90 &lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
Suppose you want to transform the columns into rows i.e. subjects become rows, use the following query:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select student_name, subject_name, mark
from #marks s
unpivot
(
  mark
  for subject_name in (English,Mathematics, Tamil,Science)
) t;&lt;/pre&gt;
&lt;div class=&quot;brush: sql;&quot;&gt;
&lt;/div&gt;
&lt;img alt=&quot;sqlserver-unpivot&quot; border=&quot;0&quot; height=&quot;251&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUOe0WMA3F8Kzi3PCclY8ouJ_I9_05_Ndh0qe5Got1Hy07WHtlthuMW-EvUBCsdbS477iBNnCm3ZWEyxPJPy7E-2QxETJHiK6FMo7o371j_hvSliO3TX4RA4qt6vA8Qr-inc10fdy-5b4O/?imgmax=800&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;sqlserver-unpivot&quot; width=&quot;254&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Note :&lt;/strong&gt; PIVOT in SQL Server basically produces a denormalised dataset whereas UNPIVOT produces normalised dataset.&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/04/pivot-unpivot-tables-sql-server.html</link><author>noreply@blogger.com (Madhivanan)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6z0qpeSZBvTZz7cxqDnFO6Q1qezQJjkTwac7Kv_XvgitJTLNk6KufXlSqH9T8xrEPCbt6k33lnJ1imIIHMZWN7HvV51FU0UptGIa-EtIFlcQkc9bwtiE_XlZyalK-SxcSPaqy5yqYiSFq/s72-c?imgmax=800" height="72" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1127924348915190833</guid><pubDate>Thu, 10 Mar 2016 15:29:00 +0000</pubDate><atom:updated>2016-03-10T07:29:04.237-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>Add an Identity to an Existing Column in large SQL Server tables</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Suppose you have a table with a large amount of data without an identity column and you want to add an IDENTITY property to the existing column. It is important to note that &lt;strong&gt;in SQL Server you cannot alter a column to have an identity property&lt;/strong&gt;. So how do we implement this? &lt;br /&gt;
&lt;br /&gt;
There are three options.&lt;br /&gt;
&lt;br /&gt;
Consider the following dataset:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table testing (id int not null, value decimal(12,2))

insert into testing(id,value)
select 1,rand()*10000 union all
select 2,rand()*10000 union all
select 3,rand()*10000 union all
select 4,rand()*10000 union all
select 5,rand()*10000&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
&lt;strong&gt;Method 1:&lt;/strong&gt; &lt;strong&gt;Add a new column with IDENTITY property:&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;alter table testing add id_new int identity(1,1);&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
Now the table &lt;i&gt;testing&lt;/i&gt; will have data with identity values and you can just use this identity column for any references.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Method 2: Create a new table with identity column and move the data over there&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table testing1 (id int identity(1,1), value decimal(12,2))

Insert into testing1(value)
select value from testing;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
Now the table &lt;i&gt;testing1 &lt;/i&gt;will have data with identity values and just like with Method 1, you can use this identity column for any reference.&lt;br /&gt;
&lt;br /&gt;&lt;strong&gt;Method 3: Use ALTER TABLE SWITCH option&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Create a new table with the same schema as that of the table &lt;em&gt;testing&lt;/em&gt; but with IDENTITY property&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table testing2 (id int identity(1,1), value decimal(12,2))&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
Now use the SWITCH option to move data to this table&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;alter table testing switch to testing2;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
Now all the data is available in &lt;i&gt;testing2 &lt;/i&gt;which has an identity column.&lt;br /&gt;
&lt;br /&gt;
Now just drop &lt;i&gt;testing &lt;/i&gt;table and rename testing2 to testing&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;drop table testing;
EXEC sp_rename &#39;testing2&#39;,&#39;testing&#39;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;
&lt;/pre&gt;
Now the table &lt;i&gt;testing &lt;/i&gt;has an IDENTITY column with all the data.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Now the question is &quot;which method is the best to use?&quot;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;
Well, Methods 1 and 2 may be time consuming if the source table has millions of rows. &lt;strong&gt;Method 3 is very fast&lt;/strong&gt; as it switches the partition from one table to another very quickly. So this method will take only few seconds compared to the other two methods.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Caveats:&lt;/strong&gt; You may need to take care of primary key - foreign key relations before using any of these methods.

  &lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/03/add-identity-to-existing-column-in.html</link><author>noreply@blogger.com (Madhivanan)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1414993663528613989</guid><pubDate>Fri, 26 Feb 2016 03:09:00 +0000</pubDate><atom:updated>2016-02-28T19:12:54.630-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">SQL Server 2014</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>CUBE and ROLLUP with GROUPBY in SQL Server</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;strong&gt;CUBE and ROLLUP are SQL Server operators&lt;/strong&gt; which are always used along with a GROUP BY clause. These operators perform multi level aggregations at each column specified in the GROUP BY Clause. ROLLUP will do aggregation in the following manner:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Operation : ROLLUP(col1,col2)
Groupings : col1,col2
            col1, ALL(NULL)
            ALL (NULL)&lt;/pre&gt;
&lt;br /&gt;
CUBE will do aggregation in the following manner:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;Operation : CUBE(col1,col2)
Groupings : col1,col2
            col1
        ALL(NULL), col2
            ALL(NULL)&lt;/pre&gt;
&lt;br /&gt;
Let us create the following dataset and explore the resultset:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;create table #sales_data(region varchar(30), sales_date datetime,&amp;nbsp;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;sales_amount decimal(12,2))

truncate table #sales_data
insert into #sales_data(region,sales_Date,sales_amount)
select &#39;South Asia&#39;, &#39;2014-01-01&#39;,30000 union all
select &#39;South Asia&#39;, &#39;2014-05-01&#39;,72000 union all
select &#39;South Asia&#39;, &#39;2015-05-01&#39;,6700 union all
select &#39;North America&#39;, &#39;2014-03-01&#39;,12500 union all
select &#39;North America&#39;, &#39;2015-05-01&#39;,80000 union all
select &#39;North America&#39;, &#39;2015-05-01&#39;,9000 union all
select &#39;Australia&#39;, &#39;2014-02-01&#39;,88000 union all
select &#39;Australia&#39;, &#39;2015-01-01&#39;,144000 union all
select &#39;Australia&#39;, &#39;2015-05-01&#39;,178000 &lt;/pre&gt;
&lt;h3&gt;
Using ROLLUP&lt;/h3&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select region, year(sales_date) as sales_year,&amp;nbsp;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;sum(sales_amount) as total_spent  from #sales_data
group by region, year(sales_date)
with ROLLUP&lt;/pre&gt;
&lt;br /&gt;
The result of the above statement is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;region                         sales_year  total_spent
------------------------------ ----------- ---------------
Australia                      2014        88000.00
Australia                      2015        322000.00
Australia                      NULL        410000.00
North America                  2014        12500.00
North America                  2015        89000.00
North America                  NULL        101500.00
South Asia                     2014        102000.00
South Asia                     2015        6700.00
South Asia                     NULL        108700.00
NULL                           NULL        620200.00&lt;/pre&gt;
&lt;br /&gt;
As you can see, Grouping is done in three cases. &lt;br /&gt;
&lt;br /&gt;
1. Grouping by the columns region and sales_year &lt;br /&gt;
2. Grouping by the columns region only &lt;br /&gt;
3. Grouping by no columns &lt;br /&gt;
&lt;h3&gt;
Using CUBE&lt;/h3&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;select region, year(sales_date) as sales_year,&amp;nbsp;&lt;/pre&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;sum(sales_amount) as total_spent  from #sales_data
group by region, year(sales_date)
with CUBE&lt;/pre&gt;
&lt;br /&gt;
The result of the above statement is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql;&quot;&gt;region                         sales_year  total_spent
------------------------------ ----------- -----------------
Australia                      2014        88000.00
North America                  2014        12500.00
South Asia                     2014        102000.00
NULL                           2014        202500.00
Australia                      2015        322000.00
North America                  2015        89000.00
South Asia                     2015        6700.00
NULL                           2015        417700.00
NULL                           NULL        620200.00
Australia                      NULL        410000.00
North America                  NULL        101500.00
South Asia                     NULL        108700.00&lt;/pre&gt;
&lt;br /&gt;
As you can see, Grouping is done in four cases. &lt;br /&gt;
&lt;br /&gt;
1. Grouping by the columns region and sales_year &lt;br /&gt;
2. Grouping by the column sales_year only &lt;br /&gt;
3. Grouping by the column region &lt;br /&gt;
4. Grouping by no columns &lt;br /&gt;
&lt;br /&gt;
You can use both of these operators to achieve aggregation at multiple levels. CUBE performs more number of aggregations with multiple combination of the grouping columns. &lt;br /&gt;
&lt;br /&gt;
If you just want to perform multiple groupings not excluding the first column, you can use ROLLUP, otherwise use CUBE.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Note:&lt;/strong&gt; Usage of &lt;strong&gt;ROLLUP and CUBE in SQL Server&lt;/strong&gt; are time-consuming options as they do groupings at multiple level. If you use a reporting tool to display the result, you should avoid doing it in SQL and do it in the reporting tool itself .&lt;/div&gt;
</description><link>http://www.sqlservercurry.com/2016/02/cube-and-rollup-with-groupby-in-sql.html</link><author>noreply@blogger.com (Madhivanan)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-1799159501251843084</guid><pubDate>Wed, 17 Feb 2016 09:31:00 +0000</pubDate><atom:updated>2016-02-17T19:30:29.898-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server - Time difference in HH hours, MM minutes and SS seconds format‏</title><description>Suppose you have two datetime values and want to express the difference in the format HH Hours, MM minutes and SS seconds. You can use CONVERT function with style 108 as shown below:   &lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;; font-size: small;&quot;&gt; declare @start_date datetime, @end_date datetime     &lt;br /&gt; select @start_date =&#39;20121210 11:19:33&#39;, @end_date=&#39;20121210 19:28:12&#39;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;; font-size: small;&quot;&gt;&lt;br /&gt;select stuff(stuff(convert(varchar(10),@end_date-@start_date,108),6,1,&#39; Minutes and &#39;),3,1,&#39; Hours, &#39;)+&#39; Seconds&#39;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;consolas&amp;quot;;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
The variables @start_date and @end_date have values for start and end times. We can directly substract @start_date from @end_date and the result is still in datetime. CONVERT with style 108 will only extract time part in the format HH:MM:SS. &lt;br /&gt;
&lt;br /&gt;
Now replace : after HH with Hours, replace : after MM with minutes and , append &#39; Seconds&#39; at the end of time and the result is at the format HH Hours, MM minutes and SS seconds. &lt;br /&gt;
&lt;br /&gt;
The result of the above code is&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;08 Hours, 08 Minutes and 39 Seconds&lt;/span&gt;</description><link>http://www.sqlservercurry.com/2013/01/sql-server-time-difference-in-hh-hours.html</link><author>noreply@blogger.com (Madhivanan)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-495177919198719500.post-2144605344609770962</guid><pubDate>Mon, 18 Jan 2016 11:28:00 +0000</pubDate><atom:updated>2016-01-25T01:40:57.050-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL Server 2012</category><category domain="http://www.blogger.com/atom/ns#">Transact SQL T-SQL</category><title>SQL Server 2012 - Binding Sequence to a Column‏</title><description>Continuing my &lt;a href=&quot;http://www.sqlservercurry.com/search/label/SQL%20Server%202012&quot;&gt;&lt;strong&gt;series on SQL Server 2012&lt;/strong&gt;&lt;/a&gt;, today we will learn about Sequence which is an object in SQL Server 2012 and can be used to generate customized sequence numbers. Although it is independent of objects, however an object can bind it. In this post, we will see how to use that as default value for a column&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Create a sequence named my_seq&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;create sequence my_seq      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; as int       &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; start with 1       &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; increment by 1 &lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;GO&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Create a table in which one of the columns has a default value of my_seq&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;create table testing (col1 int, col2 int default next value for my_seq)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Now add some data to the table&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;insert into testing (col1)     &lt;br /&gt;select 34 union all      &lt;br /&gt;select 6&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Select data from the table and see what col2 returns&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;select * from testing&lt;/span&gt;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;img alt=&quot;result&quot; border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsm8iUqyJlA1YONyYUfq1qX9dTpivW08STG92IYMIzsZu0tToKW0Z4GtmhuKWHUTxlOqJw_AcaqkAH7YfmKhApS0JEaAUbj6BEXNruejvD4GmUFnlinbhssiRlw2hDeBk99s6bMFwFuT4/?imgmax=800&quot; height=&quot;80&quot; style=&quot;background-image: none; border: 0px currentColor; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;result&quot; width=&quot;145&quot; /&gt;&lt;br /&gt;
&lt;br /&gt;
Col2 returns unique numbers. It should be noted that if the sequence is used by many objects, the value may not be sequential i.e. some values may be used somewhere else.&lt;br /&gt;
&lt;br /&gt;
This way we can use sequence object to generate unique numbers like an identity column   </description><link>http://www.sqlservercurry.com/2012/08/sql-server-2012-binding-sequence-to.html</link><author>noreply@blogger.com (Madhivanan)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsm8iUqyJlA1YONyYUfq1qX9dTpivW08STG92IYMIzsZu0tToKW0Z4GtmhuKWHUTxlOqJw_AcaqkAH7YfmKhApS0JEaAUbj6BEXNruejvD4GmUFnlinbhssiRlw2hDeBk99s6bMFwFuT4/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item></channel></rss>