Thursday, May 2, 2013

sql server truncate table

sql server truncate table

                     truncate command in sql server deletes all records in the table. this operation is faster than delete command.
because of following reasons

delete command records deleted entries will be logged into  log file. where as truncate doesn't.

delete command fires triggers, where as truncate don't.

Once truncate occurs on a table, user cannot rollback data.
Syntax
                truncate table  [tablename];
              

Multiple table truncates

             truncate table [table1],[table2] ...[table n];

Truncate a tables associated with foreign key reference:

Steps to truncate tables associated with primary key and foreign key references.

Step 1) Truncate all child tables
Step 2) Truncate parent table.
 
Step 1)Truncate table [child table 1],[child table 2]...[child table n];
Step 2)Truncate table [parent table 1] [parent table 2] ...[parent table n];
 

Tags: sql server Truncate table,sql server truncate tables, sql server truncate table with foreign key references, sql server truncate multiple tables, truncate trigger in sql server.sql server 2012 truncate table command

Tuesday, April 30, 2013

Convert Month to Date in oracle

 Convert Month to Date in oracle

            If user has number between 1 and 12, He can convert that number to Date

Syntax:
           to_date(day,fmt)  
        


SQL> select to_date(2,'mm') from dual;

TO_DATE(2,'mm')
--------------------
01-FEB-2014


SQL> select to_date(12,'mm') from dual;

TO_DATE(12,'mm')
--------------------
01-DEC-2014


If number exceeds 12. or less than 1, user gets following error message.


ERROR at line 1:
ORA-01843: not a valid month


Tags: Convert month  to date,convert month  to Date using To_Date function,oracle convert month  to date ,oracle convert month  to date using to_date,oracle convert month  to current month date.

Convert Day to Date in oracle

Convert Day to Date in oracle

            If user has some number between 1 and 31, He can convert that number to Date

Syntax:
           to_date(day,fmt)  
        


SQL> select to_date(2,'dd') from dual;

TO_DATE(2,'DD')
--------------------
02-MAY-2014


SQL> select to_date(31,'dd') from dual;


TO_DATE(31,'DD')
--------------------

31-MAY-2014


If number exceeds 31. or less than 1, user gets following error message.


ERROR at line 1:
   ORA-01847: day of month must be between 1 and last day of month


Tags: Convert day to date,convert day to Date using To_Date function,oracle convert day to date ,
oracle convert day to date using to_date,
oracle convert day to current month date.

Calculated values in the Where Clause SQL Server

Calculated values in the Where Clause SQL Server


Calculated Values are not allowed in where clause, It should be part of inner view or join.

In Hr Schema , Display all employees who is more than 2,000 after 20% increment in their salary.

SQL> select empno,ename,Sal,(Sal+sal*20/100) as "20%" from emp e
    where e."20%">2000;
where e."20%">2000
      *
ERROR at line 2:
ORA-00904: "E"."20%": invalid identifier

In order to solve this. There are 2 methods.

                 1.Using Inner Views
                 2.Using Inner join.

Method 1:Using Inner Views

  select  * from (select empno,ename,sal,(sal+sal*20/100) as "20%" from emp) e
  where e."20%">2000

Inner view gives a table called e, using columns in table user can filter in where clause.


Method 2: Join Employees table with Inner View.

select  ec.empno,ec.ename,ec.sal,ec."20%" from emp e

inner join

(select empno,ename,sal,(sal+sal*20/100) as "20%" from emp) ec

on e.empno=ec.empno

where ec."20%">2000

This method also produces same results, I prefer method 1, because Table scan is 1.

Tags:Calculated values in the Where Clause sql server ,Filter based on calculated value, compute column in where clause, join table and inner view, inner views in sql server , filter based on pseudo column.

Monday, April 29, 2013

SQL Server Case Statement

SQL Server  2012 Case Statement

                             Case statement combines multiple IF THEN ELSE statements into single statement for better readability, It can be used search single column or multiple columns

Syntax: Single Column Case Statement

select col1,col2, case  col3
                            when condition1 then msg1
                             when condition2 then msg2   
                             else msg3
                             end    from [tablename]


Example: Using case statement Display message as job title and name


select ename,empno, case  JOB
when 'CLERK' THEN CONCAT(ENAME,' IS A ',JOB)
when 'SALESMAN' THEN CONCAT(ENAME,' IS A ',JOB)
when 'MANAGER' THEN CONCAT(ENAME,' IS A ',JOB)
when 'PRESIDENT' THEN CONCAT(ENAME,' IS A ',JOB)
when 'ANALYST' THEN CONCAT(ENAME,' IS A ',JOB)
end AS "JOB"

 from emp


OUTPUT

EmpName             Emp Number        JOB
-------------------------------------------------------------------------
SMITH                   7369                    SMITH IS A CLERK
ALLEN                   7499                    ALLEN IS A SALESMAN
WARD                    7521                    WARD IS A SALESMAN
JONES                   7566                    JONES IS A MANAGER
MARTIN                  7654                    MARTIN IS A SALESMAN
BLAKE                   7698                    BLAKE IS A MANAGER
CLARK                   7782                    CLARK IS A MANAGER
KING                    7839                    KING IS A PRESIDENT
TURNER                  7844                    TURNER IS A SALESMAN
JAMES                   7900                    JAMES IS A CLERK
FORD                    7902                    FORD IS A ANALYST
MILLER                  7934                    MILLER IS A CLERK



Example:Case statement with Multiple conditions

Syntax:
                         case
                             when boolean exp then msg1;
                             when boolean exp then msg2;
                          end

                              
   Boolean expression in CASE statement/multiple conditions in Case statement

 select ename,empno,SAL, case 
when JOB='CLERK' AND SAL >=800 THEN CONCAT(ENAME,' IS A ',JOB)
when JOB='SALESMAN' AND SAL >=1200 THEN CONCAT(ENAME,' IS A ',JOB)
when JOB='MANAGER'AND SAL >=2000 THEN CONCAT(ENAME,' IS A ',JOB)
when JOB='PRESIDENT'AND SAL >=4000 THEN CONCAT(ENAME,' IS A ',JOB)
when JOB='ANALYST' AND SAL >=2500 THEN CONCAT(ENAME,' IS A ',JOB)
END AS "JOB"
 from emp

OUTPUT:              
ename    empno    SAL    JOB
---------------------------------------------
SMITH    7369    800.00       SMITH IS A CLERK
ALLEN    7499    1600.00     ALLEN IS A SALESMAN
WARD    7521    1250.00      WARD IS A SALESMAN
JONES    7566    2975.00       JONES IS A MANAGER
MARTIN    7654    1250.00    MARTIN IS A SALESMAN
BLAKE    7698    2850.00      BLAKE IS A MANAGER
CLARK    7782    2450.00     CLARK IS A MANAGER
KING    7839    5000.00         KING IS A PRESIDENT
TURNER    7844    1500.00    TURNER IS A SALESMAN
JAMES    7900    950.00          JAMES IS A CLERK
FORD    7902    3000.00          FORD IS A ANALYST
MILLER    7934    1300.00     MILLER IS A CLERK

                               

Tags:SQL Server Case Statement ,T-SQL case statement, using Case statement in select statement,
case statement with single column, case statement with multiple conditions,How to use case statement in T-SQL,How to use case statement in SQL SERVER 2012.

SQL Server Ranking Functions

SQL Server Ranking Functions

                       

ROW_NUMBER    RANK DENSE_RANK NTILE

Sunday, April 28, 2013

SQL SERVER Bit field Data Type

SQL SERVER Bit field Data Type 

                   SQL Server bit field data type is used to store Boolean values . i.e true or false.
Note: SQL Server doesn't support Yes or No. 


      TRUE  -->  1
       FALSE -->  0


Example 1:

Declare @b bit = 1;
select @b

Example 2;

declare @b bit= cast('true' as bit)
select @b

Example 3:
Create table bdemo([status] bit);

insert into bdemo(1);
insert into bdemo(0);
insert into bdemo(cast('true' as bit));
insert into bdemo(cast('false' as bit));
declare @b char='1';
insert into bdemo values(@b);  --implicit conversion from char to bit

Example 4: Boolean Data Type falls under Number data type.
declare @b bit=false;
select ISNUMERIC(@b)

displays 1

Example 5: Implicit Converting char to bit data type

declare @b char(1) = '1';select ISNUMERIC(@b)
displays 1,

Tags:  SQL SERVER Bit field Data Type ,SQL Server boolean Data Types, char to bit field conversion in sql server, inserting into bit field column,

Temporary Tables in SQL SERVER 2012

SQL SERVER Temporary Tables.

                       SQL Server Temporary tables are used to store table information in Temp Database. These temporary tables are shot lived i.e up to the session time,   once session is closed these tables are automatically dropped and data will be deleted.

There are 2 types of temorary tables
  1.                Local Temporary tables
  2.                Global Temporary tables.

Local Temporary tables:

   These tables are represented as '#tablename'  lives up to session time, once session is closed tables will be deleted automatically.   User cannot access these tables in another session.
  Note: temporary table can be deleted using Drop table #tablename;

select * into  #tbl  from emp;

Table structure and data will be copied to #tbl . this table located in Temp DB.

Manual Dropping of local temporary tables.

drop table #tbl.

Global Temporary tables.

             Global temporary tables also same as Local temporary tables, which are denoted as 
##tablename in the beginning.  It can be accessed in another query wizard, once all sessions/query wizards/connections are closed, these tables are automatically dropped.

select * into ##tbl2 from emp;

Manual Dropping of Global temporary tables.

drop table ##tablename.


TAGS:Temporary Tables in SQL SERVER,SQL Server temporary tables, SQL Server local temporary tables, SQL Server global temporary tables, Dropping temporary tables,Dropping local temporary table, dropping global temporary tables.Select into clause, Creating temporary table using Select into clause.

SQL SERVER WHILE LOOP

While loops in SQL SERVER T-SQL

            while loops are mainly used for executing block of sql statements for specified number of times.

SYNTAX:
  while condition
   begin
            block of  sql statements
   end;


For ex: Print Even numbers from 1 to 20 using while loop.


declare @counter int=1;

while @counter <=20
begin

if (@counter % 2 = 0)
print 'even number'+cast(@counter as varchar(2));


set @counter=@counter+1;
end

OUTPUT
even number2
even number4
even number6
even number8
even number10
even number12
even number14
even number16
even number18
even number20

For ex: Print ODD numbers from 1 to 20 using while loop.

 declare @counter int=1;

while @counter <=20
begin

if (@counter % 2 <> 0)
print 'odd number'+cast(@counter as varchar(2));

set @counter=@counter+1;
end


OUTPUT
odd number1
odd number3
odd number5
odd number7
odd number9
odd number11
odd number13
odd number15
odd number17
odd number19



SQL SERVER T-SQL EXCEPTIONS HANDLING IN WHILE LOOP

SQL SERVER EXCEPTIONS HANDLING IN WHILE LOOP


FOR EX:  tinyint datatype holds values  from 0 to 255. if value exceeds 255, throws an exception saying "Arithmetic overflow error for data type tinyint, value = 256.' to data type int"  and resets the value to 0,
In order to catch such type of exceptions.


declare @count tinyint=0;

begin try
while @count <= 255
begin

print @count;


set @count = @count+1;
end
end try
 
begin catch

print @@error+ERROR_MESSAGE()
end catch

Note: If exceptions are not trapped it will be in an infinite loop, because @counter will be reset to 0.

OUTPUT
0
1
..
..
. ..
252
253
254
255
Msg 245, Level 16, State 1, Line 16
Conversion failed when converting the nvarchar value 'Arithmetic overflow error for data type tinyint, value = 256.' to data type int.

TAGS: BEGIN TRY in WHILE LOOP,Catching exceptions in T-SQL, SQL Server exceptions,END TRY,  BEGIN CATCH in SQL SERVER, END CATCH IN SQL SERVER,
SQL SERVER T-SQL EXCEPTIONS,

Friday, April 26, 2013

SQL SERVER DROP TABLE

SQL SERVER DROP TABLE.

                              SQL Server Drop Table , drops the table from the database. ie dropping data+structure of the table.
This operation is permanent, ie Once table is dropped, user cannot get it back.

SYNTAX:
              Drop table [dbname].[schema].[tablename];


For ex:   Drop table customers
           drop table  [dbo].[customers]

   uses current database.

Note: if ur table is not associated with any schema. then [dbo]
 is default schema. u can ignore this also.
simply   drop table [tablename]

Drop table customer associated with profile schema.

drop table [profile].[customer].

uses current database.

Check before dropping a table using Object_ID

if (OBJECT_ID(N'sports','U') is not null)
begin
            print 'sports table exists and dropping' 
            drop table sports;
end

Object_ID tables 2 arguments 
                    1.table name
                     2.type in this case User Defined table , so 'U'

Drop table which has spaces in table name.i.e "order details"

Drop table [order details];


Drop table which has square brackets in it. i.e '[customer]'

 drop table [[customer]]]

 

 DROP Table which has Foreign and Primary Key relationships.

1.First drop all child tables.
2.Second drop parent table.


otherwise Exception will be thrown "Msg 3726, Level 16, State 1, Line 12
Could not drop object 'tablename' because it is referenced by a FOREIGN KEY constraint."
 for ex: drop table [child table1],[child table2],....[parent table]

DROP MULTIPLE TABLE


Drop table  [table1],[table2] ....

TAGS: SQL SERVER DROP TABLE, SQL SERVER DROP TABLE SYNTAX, DROP Multiple tables in SQL SERVER, DROP Parent child tables in SQL SERVER.

SQL Server Insert Multiple Records

SQL Server Insert Multiple Records

SQL Server INSERT DML operation allows user to add multiple records in one statement.

 

Syntax:

insert into [tablename]  values (),(),()

   or

insert into [table1]  select * from [table2]


for ex: Create a Sports Table

CREATE TABLE [dbo].[Sports] (
    [Id]      INT          IDENTITY (1, 1) NOT NULL,
    [Name]    VARCHAR (20) NOT NULL,
    [Country] NCHAR (2)    NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


Insert multiple records into Sports table 



insert into sports values
 (N'Tennis', N'IN'),
 (N'Hockey', N'IN'),
 (N'Football', N'IN'),
 (N'BaseBall', N'US'),
 (N'Hand FoodBall', N'US'),
 (N'Cricket', N'IN'),
 (N'Cricket', N'UK'),
 (N'Basket Ball', N'UK'),


Select * from sports

IDNameCountry
23 Tennis IN
24 Hockey IN
25 Football IN
26 BaseBall US
27 Hand FoodBall US
28 Cricket IN
29 Cricket UK
30 Basket Ball UK


METHOD 2:  Inserting multiple records from another table(s).


insert into [table 1] select * from [table2]  etc.,






Tags: SQL Server Insert Multiple Records, Inserting multiple records using INSERT statement, Inserting multiple records using Select statement, Inserting bulk rows into table, using INSERT command inserting multiple records.

SQL Server Insert command

SQL Server Insert command

Create Table from Another Table in SQL Server

Create Table from Another Table  in SQL Server

Create Table in SQL SERVER

Create Table in SQL SERVER

CREATE DATABASE On SQL SERVER

CREATE DATABASE On SQL SERVER

CREATE DATABASE On SQL SERVER

CREATE DATABASE On SQL SERVER

SQL Server LEFT OUTER JOIN

SQL Server LEFT OUTER JOIN

SQL Server Left Outer Join displays all rows from Left table.

SYNATX:

SELECT * FROM 
[Table 1]
LEFT OUTER JOIN 
[Table 2]
ON CONDITION.

 For ex: Employee belongs to One Department.

If Table 1 is Department , then SQL Server Left outer join displays all rows from Department table.

select * from 
Dept
LEFT OUTER JOIN
Emp
on DEPT.DEPTNO=EMP.DEPTNO;

 




SQL Server FULL OUTER JOIN

SQL Server FULL OUTER JOIN

               SQL Server FULL OUTER JOIN joins tables on matching condition and non-matching rows from parent table with null values from child table.i.e both side data will be displayed.
All data from parent table on matched condition and non-macthed rows from parent table with null value in child table.

for ex:  Employee should belong to Department.

Here Department is Parent Table and Employee is Child Table.

Whenever u perform FULL OUTER JOIN, all rows from parent table(DEPT) will be displayed



SQL SERVER INNER JOIN

SQL SERVER INNER JOIN
                   Inner join used to join tables based on common keys.

INNER JOIN SYNTAX:-

select * from table 1
inner join
table 2
on condition


EMP TABLE

EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO
7369SMITHCLERK790212/17/1980 12:00:00 AM800.00
20
7499ALLENSALESMAN76982/20/1981 12:00:00 AM1600.00300.0030
7521WARDSALESMAN76982/22/1981 12:00:00 AM1250.00500.0030
7566JONESMANAGER78394/2/1981 12:00:00 AM2975.00
20
7654MARTINSALESMAN76989/28/1981 12:00:00 AM1250.001400.0030
7698BLAKEMANAGER78395/1/1981 12:00:00 AM2850.00
30
7782CLARKMANAGER78396/9/1981 12:00:00 AM2450.00
10
7839KINGPRESIDENT
11/17/1981 12:00:00 AM5000.00
10
7844TURNERSALESMAN76989/8/1981 12:00:00 AM1500.000.0030
7900JAMESCLERK769812/3/1981 12:00:00 AM950.00
30
7902FORDANALYST756612/3/1981 12:00:00 AM3000.00
20
7934MILLERCLERK77821/23/1982 12:00:00 AM1300.00
10


DEPT TABLE


Dept IDDept NameDept Loc
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

>Get Employee & Department Details

Select * from EMP
inner join
Dept
on EMP.DEPTNO=DEPT.DEPTNO


Empno ENAME JOB MGR HIREDATE SAL COMM DEPTNO DEPTNO DNAME LOC ---- ---- ------ ----- ---- -------------------------------------------------- ----- ---- -------------------- ----- ---- ------ ----- ---- ---------- ----- ---- --------------------------------------- ----- ---- --------------------------------------- ----- ---- ------ ----- ---- ------ ----- ---- -------------------------------------------------- ----- ---- -------------------------------------------------- ----- -----
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30 30 SALES CHICAGO
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30 30 SALES CHICAGO
7566 JONES MANAGER 7839 1981-04-02 2975.00 300.00 20 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30 30 SALES CHICAGO
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30 30 SALES CHICAGO
7782 CLARK MANAGER 7839 1981-06-09 2450.00 100.00 10 10 ACCOUNTING NEW YORK
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30 30 SALES CHICAGO
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30 30 SALES CHICAGO
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20 20 RESEARCH DALLAS
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10 10 ACCOUNTING NEW YORK

>Get DEPT Details with Employee Count.

select d.deptno,dname,loc,e."Emp Count"  from dept d
inner join
(select deptno,count(*) "Emp Count" from emp group by deptno) e
on d.deptno = e.deptno;
 


10 ACCOUNTING NEW YORK 3
20 RESEARCH DALLAS 3
30 SALES CHICAGO 6


Tags: SQLServer inner join, SQL Server JOINS, SQL Server Inner join on common keys, SQL Server Inner Join on foreign keys of child table and Primary keys of parent table.

Thursday, April 25, 2013

SQL Server SUM function

SQL Server SUM function

SQL Server 2012 Sums numeric columns and ignores null values.

Price     Item
10.11     shoes
11.22      shirts
NULL    Trousers
33.33     Shorts


select SUM(price)  ->  gives 54.66

>>select total salary of the Employees

select sum(sal) "Total Salary" from emp

 Total Salary
24925.00

>>Select Total Salary of the Employees by Department

select deptno,sum(sal) "Total Salary by Department" from emp
group by deptno

deptno    "Total Salary by Department"
10    8750.00
20    6775.00
30    9400.00

>Get Total Salary and Commission department wise.

select deptno,sum(sal) "Salary",
                      sum(comm) "Comm",
                      sum(sal)+sum(comm) "Sal+comm" from emp
group by deptno

deptno    Salary    Comm    Sal+comm
10    8750.00    100.00    8850.00
20    6775.00    300.00    7075.00
30    9400.00    2200.00    11600.00

Tags: Using SQL Server SUm function, Using SUM aggregate function, How to use SQL Server aggregate function SUM, SQL Server Aggregate functions

CHECK TODAY IS SATURDAY OR SUN DAY in SQL SERVER 2012.

CHECK TODAY IS SATURDAY OR SUN DAY in SQL SERVER 2012.


The following script gets today's date using getdate() function.
Format function return Short day of the today's date. and If condition checks if today's day falls in Sat/sun. Displays appropriate message.

 


declare @today varchar(3);
set @today = FORMAT(getdate(),'ddd') --ddd gives short day.
select @today  --display

if( @today in ('Sat','Sun'))
print 'Today is '+@today
else print 'Today is not saturday/sunday but '+@today+' day';


OUTPUT:  if Today is Friday

Today is not saturday/sunday but Fri day

ex 2: if Today is Saturday

Today is Sat.


Tags: CHECK TODAY IS SATURDAY OR SUN DAY in SQL SERVER 2012. Display Day in short form, using Format Function in SQL Server, T-SQL IN clause,Using T-SQL IF condition,

Get Last Day of the Month in SQL Server 2012

Get Last Day of the Month in SQL Server 2012

SQL Server Provides EOMONTH  function to get LAST of the MONTH.  

 Synatx:  Date EOMONTH(Date) 

select EOMONTH(getdate()) "Last Date of the Month"


for ex:  2013-03-31  //output


Next MONTH  last Date

Select EOMONTH(getdate(),1)  "Next Month Last Date"
for ex: 2013-04-30 

Previous Month last date

Select EOMONTH(getdate(),-1)  "Previous Month Last Date"
for ex: 2013-02-28.

Like this User can find any date's Last Day of that Year and Month.
 
Full Syanx:  EOMONTH(DATE,[Months to Add]  return DATE.


Tags: Get last day of the Month in SQL Server 2012, Get Last Date of the Month in SQL Server,
           Get Last day of the Previous Month in SQL Server 2012, Get Last day of the Next Month in SQL Server 2012.

Get DAY in SQL Server


 Get DAY in SQL Server 2012



Using Day function  User can get Day of the Month

for ex:   Day(Getdate())

select Day(getdate()) "Day of the Month"

for ex: 4



Tags:  Get DAY in SQL Server , Get Day of the Month in SQL Server 2012

Get Current Month in SQL Server

Get Current Month in SQL Server



Using Month function  User can get current Year.

for ex:   Month(Getdate())

select Month(getdate()) "Current Month"

for ex: 4



Tags: Get Current Month  in SQL Server, Today's Month  in SQL Server, Current Month  in SQL Server, How to get current Month  in SQL Server .  Month  function in T-SQL,SQL SERVER 2012

Get Current Year in SQL Server

Get Current Year in SQL Server



Using Year function  User can get current Year.

for ex:   Year(Getdate())

select Year(getdate()) "Current Year"

for ex: 2013



Tags: Get Current Year in SQL Server, Year Today in SQL Server, Current Year in SQL Server, How to get current year in SQL Server .  YEAR function in T-SQL,SQL SERVER 2012

SQL Server Get Today's Date and Time



Using GetDate() function  User can get Today's date and time in SQL Server 2012.

select GetDate()  "Today's Date and Time"

Today's Date and Time
2013-04-25 23:13:11.143

Format: yyyy-MM-dd HH:mm:ss.fff

yyyy ->  4 digit year
MM -> 2 digit Month
dd ->  2 digit date

HH -> 24-hr format Hour
mm-> 2 digit minutes
ss -> 2 digit seconds
fff -> fraction of seconds/Milli seconds

Note: Format Specification is case sensitive.


Tags: SQl Server Get Today's date and time, Get Today's date in SQL Server, Get Time in sql server,
Get Today's date and time in sql server,Get current date and time in SQL Server.

SQL SERVER GROUP BY on DATETIME COLUMN

SQL SERVER GROUP BY -> is used to aggregate data.

For ex:  Aggregate data on List of Orders generated in a perticular Day,Month,Year etc.,
            or List of Employees in each department.

             etc.,

Group By on DateTime Column

Person Table following Data.

idNameDate of Birth
1 Peter 1997-12-12 00:00:00.000
2 Daniel 2000-01-12 00:00:00.000
2 shyam purru 2000-01-12 00:00:00.000
3 Jhon 2002-11-01 00:00:00.000
4 Jhony 1960-08-30 00:00:00.000
5 pearson 2013-04-21 00:19:32.257


Group By Year

select  Datepart(year,dob) "Year",count(*) "Count" from [profiledb].[dbo].Person
group by   Datepart(year,dob)

YearCount
1960 1
1997 1
2000 2
2002 1
2013 1

Group By Year and Then By Month

select Datepart(year,dob) "Year",
          DateName(month,dob) "Month",
          count(*) "Count" from
                         [profiledb].[dbo].Person
group by   Datepart(year,dob),
DateName(month,dob)

OUTPUT
YearMonthCount
2013 April 1
1960 August 1
1997 December 1
2000 January 2
2002 November 1

Note: Groups Data on Year and then groups by month.


Tags:SQL SERVER GROUP BY on DATETIME COLUMN,SQL Server Group By DatePart,
DatePart year,Group By on Year,Group by on Month, Group By year,month.

Wednesday, April 24, 2013

Create SEQUENCE in SQL Server 2012

Create Sequence in SQL Server 2012.

          SQL Server 2012   Sequence object gives sequences numbers of User choice. i.e
It has start value property, increment by , Minimum ,Maximum Value Properties.
Its not associated with table column, But associated with schema.


In addition user can specify datatype(tinyint,smallint,int,bigint,decimal and numeric with scale of 0, or user defined type.)

By default: bigint

Syntax:

             Create Sequence <Sequence name> [start with <value> increment by <value> MinValue <value> MaxValue <value>];

Create sequence with datatype Syntax

create sequence <sequence_name> as tinyint  start with <value>;

Note: Sequence Range depends on Datatype used.

for ex: for tinint MinValue is 0 Max Value is 255.
           for int MIN VALUE -2,147,483,648  MAX VALUE. 2,147,483,647
           etc.,


For ex:  Create Sequence start value as 1.

 Create Sequence sequence1  start with 1;

select    next value for sequence1   -- outputs 1 ,next execution 2 etc.,

For ex:  Create Sequence with start value , Minimum and Maximum values.

1.  Create Sequence sequence2  start with 1  MinValue 1 MaxValue 100;



For ex:  Create Sequence start value , Increment , Minimum and Maximum values.

1.  Create Sequence sequence3  start with 1 increment by 1 MinValue 1 MaxValue 100;

For ex:  Create Sequence start value , Increment by 2, Minimum and Maximum values.

1.  Create Sequence sequence4  start with 1 increment by 2 MinValue 1 MaxValue 100;


For ex:  Create Sequence start value as -1 , Increment by 2, Minimum and Maximum values.

Create Sequence sequence4  start with -1 increment by -2 MinValue -100 ;
select next value for sequence4  //outputs from -1, next -3 ,-5 etc.,


SEQUENCE VALUE IN INSERT STATEMENT

INSERT INTO SPORTS(ID,NAME,COUNTRY) VALUES(NEXT VALUE FOR SEQUENCE1,
'HAND FOODBALL','US');

ASSUMING ID COLUMN IS NOT IDENTITY COLUMN if so set IDENTITY_INSERT IS on.


SEQUENCE VALUE IN UPDATE STATEMENT

UPDATE SPORTS SET ID=NEXT VALUE FOR SEQUENCE4 WHERE ID=23;


RESET SEQUENCE VALUE

Create sequence seq1 start with 1;
select next value for seq1 ;   outputs  1, next time 2,3

If u want to reset the Sequence value   use alter sequence

alter sequence seq1 restart with 1

select next value for seq1; again outputs 1,2,3 etc.,

CHANGE MINIMUM VALUE IN SEQUENCE

alter sequence seq1 MINVALUE 5;

user may be error message "
The current value '1' for alter sequence seq1 Minvalue 5sequence object 'seq1' must be between the minimum and maximum value of the sequence object.
"
so start value should be between minimum and maximum value.

alter sequence seq1 RESTART with 6 MINVALUE 5;

select next value for seq1 outputs  6,7,8 etc.,

CHANGE MAXIMUM VALUE IN SEQUENCE.

alter sequence seq1 MAXVALUE 10

 Note:Maximum value should be greater than  Minimum value.


DROP THE SEQUENCE

Drop Sequence <sequenceName>

Get all Sequences in the Database

select * from sys.sequences.

Get Current Value of the Sequence.

select current_value from sys.sequences where name ='<sequence_name>';

Get Maximum Minimum Values of the Sequence

select minimum_value,maximum_value from sys.sequences where name ='<sequence_name>';


Tags: Create SEQUENCE in SQL Server 2012,Get Maximum Value of the Sequence,Get Minimum Value of the Sequence,Get all sequences in the database,Drop the Sequence,Change Maximum value of the Sequence,Create Sequence,Create sequence with datatype,

Tuesday, April 23, 2013

Get words from a String using PatIndex in SQL SERVER

Get words from a String using PatIndex in SQL SERVER


This tutorial gets words from a String/text column, Splits a string using space as a delimiter.  
Using PatIndex string function which returns delimiter's first position. then remove each word from the string.



declare @sentence varchar(250)=N'hello this is my world';

declare @sidx int = 1, @len int= len(@sentence);
declare @lidx int = @len;

--Getting words from a String Changing Original Text

while @sentence is not null
begin

             set @lidx=patindex('%['' '']%',@sentence);

             if(@lidx<>0)

             print 'Word:'+substring(@sentence,@sidx,@lidx);
             else print 'Word:'+substring(@sentence,@sidx,@len);

             set @sentence = ltrim(substring(@sentence,@lidx,@len-@lidx+1));
             set @len= len(@sentence);
             if(@lidx =0) Set @sentence = NULL;
end;



OUTPUT

Word:hello
Word:this
Word:is
Word:my
Word:world



Tags: Get words from a String using T-SQL ,
Getting words from a String using T-SQL ,Splitting a string into words in sql-server, using PatIndex in sql server.

Delete Duplicate Rows from a table in SQL SERVER 2012

Delete Duplicate Rows from a table in SQL SERVER 2012

1) Create a table called Person 

CREATE TABLE [dbo].[Person] (
    [Name] VARCHAR (20) NULL,
    [idd]  INT          IDENTITY (1, 1) NOT NULL
);

2) Insert data to Person Table

insert into person(name) values('Paul'),('Jhonson'),('jenny'),('mathew')

3) Select * from Person

Name    idd
Paul    1
Jhonson    2
jenny    3
mathew    4

4) Repeat the Name column with the following command

insert into person(name) select name from person

5) select * from Person

Name    idd
Paul    1
Jhonson    2
jenny    3
mathew    4
Paul    9
Jhonson    10
jenny    11
mathew    12

Here step 4 records are repeated with same name but different IDD column values.
 
6) Display repeated rows 

Displays repeated name records here so that you can delete those records.
 
select * from persond p where idd in (select max(idd) from persond

group by name)


Name    idd
Paul    9
Jhonson    10
jenny    11
mathew    12
 
the above rows has repeated  names .(this step is for testing purpose only)

 
7) Delete Duplicate Name column values

delete  from person  where idd in (select max(idd) from person
group by name)


8) select * from person

Name    idd
Paul    1
Jhonson    2
jenny    3
mathew    4


Tags: Delete Duplicate Rows from a table in SQL SERVER 2012,Delete duplicate columns from a table, Create table in sql server, create column with identity value,remove duplicate columns, How to remove duplicate records from a table in sql server 2012.

How to Add Identity to Existing Column

How to Add Identity to Existing Column

 

You can not add Identity to an existing column,

you can drop the column using

alter table [tablename] drop column [columnname]  

add new column with Identity

alter table [tablename] add col int identity(1,1)

for ex:

alter table [dbo].[person] add IDD int identity(1,1);


Tags: How to Add Identity to Existing Column,Alter table ,drop column in sql server,add new column with identity,add  new column to a table using alter table command.

Remove Duplicate Rows from a Table in SQL SERVER 2012

Remove Duplicate Rows from a Table in SQL SERVER 2012


1)Create a table called Person

CREATE TABLE [dbo].[Person] (
    [Id]   INT          NULL,
    [Name] VARCHAR (20) NULL
);


This example works if table has all columns  repeated. and it is efficient, if user has small amount of data.


2) Insert records into Person table

insert into person values(1,'Paul'),(2,'Jhonson'),(3,'jenny'),(4,'mathew')

3) select * from Person

Id    Name
1    Paul
2    Jhonson
3    jenny
4    mathew

4) Replicate all these rows again.

insert into person select * from person

5)  select * from Person

Id    Name
1    Paul
2    Jhonson
3    jenny
4    mathew
1    Paul
2    Jhonson
3    jenny
4    mathew

6)   Display Unique Records using Distinct /group by

select distinct id,name  from persond;

Id    Name
1    Paul
2    Jhonson
3    jenny
4    mathew

7)   Copy these unique values to temporary Table

select distinct id,name into #tmp from persond;

9)  Truncate Original Table

truncate table person;

10) Copy back from temporary table to original table.

insert into person select * from #tmp;


11) Table with all unique values.

select * from Person

Id    Name
1    Paul
2    Jhonson
3    jenny
4    mathew



Tags:Remove Duplicate Rows from a Table in SQL SERVER 2012,Remove Duplicate Rows from a Table  all columns has duplicate values , display unique values using distinct,display unique records using distinct,display unique values using group by,display unique records using group by.delete duplicate records from a table in sql server.

Get Words from String SQL Server 2012

Get Words from String SQL Server 2012


Getting Words from a String/column taking space as a delimiter. Here is the Script.

It can be done 2 ways. In this example used CharIndex and SubString functions,CharIndex returns
character position in the String,SubString returns subString of the string ,you need to specify starting location and length/portion of the String.


Method1: Getting Words from a String with changing positions

declare @sentence varchar(250)=N'hello this is my world';
declare @sidx int=1,@lidx int=len(@sentence);
declare @len int = len(@sentence);


while @lidx != 0
begin


--find first space char
set @lidx=CHARINDEX(' ',@sentence,@sidx);




if(@lidx <>0)
print 'word:'+ltrim(rtrim(substring(@sentence,@sidx,@lidx-@sidx)));
else print 'word:'+ltrim(rtrim(substring(@sentence,@sidx,@len-@lidx)));

--change starting loc
set @sidx = @lidx+1;

--change ending index
if(@lidx <> 0)
set @lidx =@len;

end

Output:
word:hello
word:this
word:is
word:my
word:world

Method 2:Getting Words from a String with changing Source String.


declare @sentence varchar(250)=N'hello this is my world';

declare @sidx int = 1, @len int= len(@sentence);
declare @lidx int = @len;
--Getting words from a String Changing Original Text

while @sentence is not null
begin

             set @lidx=charindex(' ',@sentence,@sidx);

             if(@lidx<>0)

             print 'Word:'+substring(@sentence,@sidx,@lidx);
             else print 'Word:'+substring(@sentence,@sidx,@len);

             set @sentence = ltrim(substring(@sentence,@lidx,@len-@lidx+1));
             set @len= len(@sentence);
             if(@lidx =0) Set @sentence = NULL;
end;

OUTPUT:

Word:hello
Word:this
Word:is
Word:my
Word:world


Tags:Get Words from String SQL Server 2012,using charindex String function,using SubString String function,using ltrim String function in T-SQL.

Monday, April 22, 2013

How to insert values to identity column in SQL Server




Identity Columns can not be specified in Insert list because SQL Server automatically sets this value.

Cannot insert explicit value for identity column in table 'Sports' when IDENTITY_INSERT is set to OFF.

In order to Insert into Identity column



set IDENTITY_INSERT  [tablename]  ON;

insert statement here

set IDENTITY_INSERT  [tablename]  OFF;




--otherwise default nature of auto increment will not work, so u need to set to OFF.



for ex:

Set IDENTITY_INSERT  [dbo].[Sports]  ON;

Insert into Sports values(1,'Basket ball','IN');

the above insert statement throws error shown below.

 Msg 8101, Level 16, State 1, Line 2
An explicit value for the identity column in table 'Sports' can only be specified when a column list is used and IDENTITY_INSERT is ON.


so u need to specify column list in the insert statement.

Insert into Sports(ID,name,country) values(1,'Basket ball','IN');

set IDENTITY_INSERT  [dbo].[sports]  OFF;

This is how manually inserting values into Identity Column.

tags: How to insert values to identity column in SQL Server,This is how manually inserting values into Identity Column,set IDENTITY_INSERT    OFF,set IDENTITY_INSERT    ON

Check String is PalinDrome in SQL Server

How to  Check String is Palindrome in SQL Server 2012


--Insert Palindrome String here
declare @string varchar(50)=UPPER(N'ab ba');

--Find Length of the String using len
declare @length int  = len(@string);

--Find Middle Position of the String
declare @middle int = @length/2 ;

--This is required because Splitting the String into 2 pieces.
--first portion in @first last portion in @last variable.
declare @first varchar(25),@last varchar(25);

--Store first half of the String here
SELECT @first=SUBSTRING(@string,1,@middle)

-- Here logic comes
--IF string length is ODD then increment by 1
--else increment by 2, because leaving alone the exact middle letter in the String

if ( @length%2 = 0)
      set @middle = (@length/2)+1;
else set @middle = (@length/2)+2;
--Store next half string and reverse it
select @last=Reverse(SUBSTRING(@string,@middle,@length));

--testing purpose
SELECT @FIRST,@LAST,@MIDDLE,@length;

--Compare 2 Strings if they are equal or not

if( @first = @last)
  print 'both are equal ==> String is Palindrome';
else  print 'both are different ==> String is not Palindrome';


Tags: Palindrome in SQL Server , Palindrome in T-SQL, Check String is Palindrome in SQL-Server,
How to Check String is Palindrome or not in SQL Server, SQL Server String comparisions,

SQL Server Stored Procedure returning CURSOR as Output Parameter


SQL Server Stored Procedure returning CURSOR as Output Parameter


This tutorial explains How to return CURSOR as Output Paramater in SQL Server Stored Procedures. Which may not useful  for .NET Applications, It might be useful for T-SQL batch programs.


Create a Stored Procedure with Cursor as OUTPUT Param.



use profiledb

if object_ID('dbo.Get_All_Sports_In_Cursor','P') is not null
drop procedure dbo.Get_All_Sports_In_Cursor

go

create procedure Get_All_Sports_In_Cursor @p_sports_cursor cursor varying output
as

Set @p_sports_cursor = CURSOR
FORWARD_ONLY STATIC for
select * from sports;

open @p_sports_cursor;
return;





Consuming/Executing Stored Procedure which returns Cursor as Output Parameter.


USE [ProfileDB]
GO

declare @id int,@name varchar(20),@country varchar(2);
DECLARE    @return_value Int,
        @p_sports_cursor cursor

EXEC    @return_value = [dbo].[Get_All_Sports_In_Cursor]
        @p_sports_cursor = @p_sports_cursor OUTPUT

SELECT    'Return Value' = @return_value


FETCH NEXT FROM @p_sports_cursor into @id,@name,@country

while @@fetch_status =0
begin

print @concat(id,' ',@name,' ',@country)

FETCH NEXT FROM @p_sports_cursor into @id,@name,@country
end




Create a  Table called Sports

CREATE TABLE [dbo].[Sports] (
    [Id]      INT          IDENTITY (1, 1) NOT NULL primary key,
    [Name]    VARCHAR (20) NOT NULL,
    [Country] NCHAR (2)    NOT NULL,
   
);


Insert Data Into Sports table

insert into sports(name,country) values
('BaseBall','US'),('Hand FoodBall','US')

insert into sports(name,country) values
('Cricket','IN'),('Tennis','IN'),('Hockey','IN'),('Football','IN')

insert into sports(name,country) values
('Cricket','UK')

IDNameCountry
1CricketIN
2TennisIN
3HockeyIN
4FootballIN
5BaseBallUS
6Hand FoodBallUS
7CricketUK



After Excuting  Stored Procedure OUTPUT would be

OUTPUT:
1 Cricket IN
2 Tennis IN
3 Hockey IN
4 Football IN
5 BaseBall US
6 Hand FoodBall US
7 Cricket UK


Tags: SQL Server Stored Procedure returning CURSOR as Output Parameter, Stored Procedure returning Cursor as Output Parameter, How to return CURSOR as Output Parameter, Creating SQL Server Stored Procedure, Executing SQL Server Stored Procedure ,SQL Server 2012 stored Procedures, Dropping Stored Procedures.

Update Trigger in SQL SERVER 2012 for multiple rows custom message

Update Trigger in SQL SERVER 2012 for multiple rows custom message

This tutorial explains how to display custom message for each row being updated which are available in inserted and deleted tables of trigger body.

Create a  Table called Sports

CREATE TABLE [dbo].[Sports] (
    [Id]      INT          IDENTITY (1, 1) NOT NULL primary key,
    [Name]    VARCHAR (20) NOT NULL,
    [Country] NCHAR (2)    NOT NULL,
   
);


Insert Data Into Sports table

insert into sports(name,country) values
('BaseBall','US'),('Hand FoodBall','US')

insert into sports(name,country) values
('Kricket','IN'),('Tennis','IN'),('Hockey','IN'),('Football','IN')

insert into sports(name,country) values
('Kricket','UK')


IDNameCountry
1 Kricket IN
2 Tennis IN
3 Hockey IN
4 Football IN
5 BaseBall US
6 Hand FoodBall US
7 Kricket UK


Update Trigger with custom message( for Each deleted row)

 This trigger gets rows from deleted and inserted(in-built tables for triggers update and delete and insert operations) tables, joins these tables based on primary key, puts these rows in cursor and processes each row ,displays custom error message.


if object_ID('[dbo].[sports_Update]','TR') is not null
drop trigger sports_Update;
go

create trigger sports_Update
on [dbo].[sports]
 for update
as

set nocount on;
Declare @msg varchar(max);
declare @oldid int,@oldname varchar(20),@oldcountry varchar(2);
declare @newid int,@newname varchar(20),@newcountry varchar(2);

Declare  update_cursor cursor  for
select * from deleted d inner join inserted i on d.Id = i.Id;


open update_cursor;

fetch next from update_cursor into @oldid,@oldname,@oldcountry,@newid,@newname,@newcountry;
while @@FETCH_STATUS = 0
begin


select  @msg=concat(@oldid,' ',@oldname,' ',@oldcountry);
print @msg+' Deleted... Rows'+ cast(@@rowcount as varchar(3));

select  @msg=concat(@newid,' ',@newname,' ',@newcountry);
print @msg+' Updated... Rows'+ cast(@@rowcount as varchar(3));

fetch next from update_cursor into @oldid,@oldname,@oldcountry,@newid,@newname,@newcountry;
end;


close update_cursor;
deallocate update_cursor;

Now UPDATE records in  Sports Table

Update Sports set name='Cricket' where name='Kricket';

You will get  Message Shown below.

21 Kricket UK Deleted... Rows1
21 Cricket UK Updated... Rows1
20 Kricket IN Deleted... Rows1
20 Cricket IN Updated... Rows1
 
   (2 row(s) affected)

Tags:  UPDATE trigger in SQL SERVER 2012,Triggers Example,Triggers Tutorial,Trigger Syntax
How to Write custom Message using Triggers.Update trigger for multiple rows ,
Display Custom message for multiple rows Update using triggers.