Search This Blog

Intersect Operation in SQL

Intersect Operation in SQL

Many times you have a requirement like you want data from two table which are in comman that means Data distinct Present in both the Tables.
It's same like Inner Join and Exist Predicate but has a advantage over that with Null Values explained Below.
For this I will create two tables

Two table Employee1 and Employee2
create table Employee1
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee1 values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000')

select * from Employee1

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000

create table Employee2
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000'),('arun','9500'),('akash','10500')

select * from Employee2

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000
6 arun        9000
7 akash      10500

Now we are Running the Intersection Query


select * from Employee1

intersect
select * from Employee2

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000

It's same like Inner Join and Exist Clause with the Advantage over them is that if both table have same values with Some Null fields in the Columns the intersect will include that row in the Result which is not in Case with Inner Joins and Exists predicate they both filtered out Null Values.
In order to include nulls in your output with inner join and Exist Predicate you have to write extra logic for that.

To check intersect with Nulls I am inserting Rows same Rows in both tables

insert into Employee1 values(null,'5000')
insert into Employee1 values(null,'5000')
insert into Employee1 values(null,'5000')

--The Reason i have inserted the values 3 times to make both row similar as we have autoincreament column in both tables but employee 1 only has 5 records and employee 2 has 7 so we have to match Empid also to make both rows similar


insert into Employee2 values(null,'5000')

Now we are Running the Intersection query again



select * from Employee1

intersect
select * from Employee2

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000
8 Null           5000

the query has included Null rows also check with inner join and exist they will exclude Nulls.




Function to Check Date Exists in Which Quarter where fiscal Year Starts other than 1 January in SQL

Function to Check Date Exists in Which Quarter where  fiscal Year Starts other than 1 January  in SQL

Yesterday i have a requirement like this where i have to calculate Numbers of Product Sold  in
Current Quarter,Previous Quarter and  Total Year.
I thought it was simple 
Using DateName function of SQL i can extract Quarters and Group by based on that.

But the condition was that in some countries the financial Year started from October 1 and ends at September 30.
so first condition is to use October 1 as First Date of Year and 30 September as Last Date of Year
and second condition was like that if the Current Date Falls in any of Quarter then that Quarter will be Considered  as current Quarter....


so for this i have to manually create quarters using DateAdd and DateDiff Functions  to check 

1-Current Date in which quarter--To get Product sold in Current Quarter 
2-Based on Current Quarter Calculating Previous Quarter
2-Based on that  will have count of Product sold in between current Quarter Previous Quarter 
and This Year i.e 1 oct to 30 sep


For this I have created a function

Input Parameter Date
Output Table with below columns
QuarterNo StartDate LastDate

Function Code

--function to calculate Current and Previous Quarters Starting and Ending Date Based on Current Date
Create FUNCTION DateinQuarter(@Date Datetime)
RETURNS @DateInQuarters TABLE
 (
   QuarterNo  nvarchar(50)      NOT NULL,--Quarter Detail Current and Previous
   StartingDate   datetime     NOT NULL,
   LastDate datetime      NOT NULL
 ) 
AS
BEGIN
declare @firstdateofyear datetime,@EndOfYear datetime,@EndofFirstQuarter  datetime,@EndofSecondQuarter datetime ,@EndofThirdQuarter datetime,@LastQuarter datetime

select @firstdateofyear=dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)),--First Date of Year i.e. October 1

@EndOfYear=dateadd(day,-1,dateadd(yy,1,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)))), --last Date of Year i.e.30 Sept

@EndofFirstQuarter=dateadd(day,-1,dateadd(mm,3,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)))) ,--31 Dec

@EndofSecondQuarter=dateadd(day,-1,dateadd(mm,6,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0))))--31 Mar
 ,
@EndofThirdQuarter=dateadd(day,-1,dateadd(mm,9,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)))),--30 June

@LastQuarter=dateadd(day,-1,dateadd(mm,12,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)))) --30 Sep



Insert into Table Based on Checking of  Current Date

--checking Date between 1 oct to 31 Dec
if (@Date between @firstdateofyear and @EndofFirstQuarter)

   INSERT INTO @DateInQuarters (QuarterNo, StartingDate, LastDate)
   values('CurrentQuarter',@firstdateofyear,@EndofFirstQuarter),
   ('PreviousQuarter',@LastQuarter+1,@firstdateofyear)

   --checking Date between 1 jan to 31 mar
 if (@Date between @EndofFirstQuarter+1 and @EndofSecondQuarter)
   
   INSERT INTO @DateInQuarters (QuarterNo, StartingDate, LastDate)
   values('CurrentQuarter',@EndofFirstQuarter+1,@EndofSecondQuarter),
   ('PreviousQuarter',@firstdateofyear,@EndofFirstQuarter)

  --checking Date between 1 apr to 30 June
if (@Date between @EndofSecondQuarter+1 and @EndofThirdQuarter)
   
   INSERT INTO @DateInQuarters (QuarterNo, StartingDate, LastDate)
   values('CurrentQuarter',@EndofSecondQuarter+1,@EndofThirdQuarter),
    ('PreviousQuarter',@EndofFirstQuarter+1,@EndofSecondQuarter)

--Checking Date Between 1 July to 30 Sep  

 if (@Date between @EndofThirdQuarter+1 and @LastQuarter)
   
   INSERT INTO @DateInQuarters (QuarterNo, StartingDate, LastDate)
   values('CurrentQuarter',@EndofThirdQuarter+1,@LastQuarter),
    ('PreviousQuarter',@EndofSecondQuarter+1,@EndofThirdQuarter)
   
   
   RETURN;
END;


select * from dbo.DateinQuarter(getdate())

Output

QuarterNo           StartingDate                                  LastDate
CurrentQuarter 2013-07-01 00:00:00.000 2013-09-30 00:00:00.000
PreviousQuarter 2013-04-01 00:00:00.000 2013-06-30 00:00:00.000

Now Notice that the current Date i.e 29-Aug-2013 Falls in Last Quarter assuming as 1 October is first Date of Year i.e 29-Aug-2013 is the last Quarter which starts from 2013-07-01 to 2013-09-30 and Previous Quarter before the Current Quarter Starts.

So i Used this Function in my Query to get Count of  Product Sold in Current Quarter,Previous Quarter and Current Year

Keep in Mind that we are assuming that our fiscal Years starts from 1 oct to sep 30

--In order to have first and Last Date of year I am Using the Above Variable 
two Variables @firstdateofyear,@EndOfYear

declare @firstdateofyear datetime,@EndOfYear datetime, @CQstartingDate datetime, @CQEndingDate datetime,@PQstartingDate Datetime,@PQEndingDate datetime 

select @firstdateofyear=dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)),
@EndOfYear=dateadd(day,-1,dateadd(yy,1,dateadd(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GetDate())), 0)))) 
  
--Capturing Current Quarter  Starting and Ending Date given by Function DateinQuarter

select @CQstartingDate=startingDate,@CQEndingDate=LastDate  from dbo.DateinQuarter(GETDATE()) where quarterno like 'currentquarter'

--Capturing Previous Quarter  Starting and Ending Date given by Function DateinQuarter

select @PQstartingDate=startingDate,@PQEndingDate=LastDate  from dbo.DateinQuarter(GETDATE()) where quarterno like 'previousquarter' 

--Here I have Used Distinct to get count of only distinct ProductSold.

 Select  
Count(distinct CASE WHEN [ProductSoldDate] between @firstdateofyear and @EndOfYear THEN  ProductName END) AS ThisYear,
Count( distinct CASE WHEN [ProductSoldDate] between @CQstartingDate and @CQEndingDate  THEN  ProductName END) AS ThisQuarter,
Count(distinct CASE WHEN [ProductSoldDate]  between @PQstartingDate and @PQEndingDate THEN  ProductName END) AS LastQuarter
FROM Products.

Output

ThisYear ThisQuarter LastQuarter
123            115                        96

Note: You can GetQuarter Names Using Datepart Functions also but here we are Using 1 october as first date of years thats why we have created a Function

The Reason I have Blogged on this as i want to save developer time So to use this function as a reference where they are facing Same Issue like me.



Error Handling Using Try and Catch in SQL

Error Handling Using Try and Catch in SQL

In order to handle Errrors in your TSQL code SQl has provide a Tool Try and Catch that was introduced in SQL 2005.
You will place your code in Try Block which Starts with Begin Try if the code doesn't have any Error 
the complete Catch block is skipped, but in Case if there is an Error in the code inside Try Block then 
Control is Passed to Catch Block.

Let me Explain through an Example

Begin Try
Print 2/2
Print 'Succesful'
End  Try
Begin Catch
Print 'Unsuccesful'
End Catch

Output
1
Succesful

You noticed that there was no error in try Block so it skipped the catch Block Now we will generate an error in try Block in next statement

Begin Try
Print 2/0 --Divide by zero Exception
Print 'Succesful'
End  Try
Begin Catch
Print 'Unsuccesful'
End Catch

Output
UnSuccesful

There was a divide by zero exception in try block then the control went to Catch block where you have shown a custom message like Unsuccesful
If you want to Show sql Error Number and SQL Error Message instead of your custom message whenver an Error Occurs in Try BLock you can  Use like this

Begin Try
print 2/0
Print 'Succesful'
End  Try
Begin Catch
SELECT 
   ERROR_NUMBER() AS ErrorNumber
   ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

--For most of the error sql has stored an error no. and message based on that it's displaying no. and msg

Output
ErrorNumber ErrorMessage
8134          Divide by zero error encountered.

How to Use Error Handling with DML Operations

For this I will create a Table

create table Employee_ErrorHandling
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)

Now the Insert statement i will keep inside try block to handle Error of Try 
Empsalary is a Float field i will try to insert an alphanumeric field in that column

begin try
insert into Employee_ErrorHandling values('Arun','xyz')
end try
begin catch
SELECT 
   ERROR_NUMBER() AS ErrorNumber
   ,ERROR_MESSAGE() AS ErrorMessage;
end catch

Output
ErrorNumber ErrorMessage
8114 Error converting data type varchar to float.

--Remove alphanumeric data change it to float the code will run without any error no. and message

begin try
insert into Employee_ErrorHandling values('Arun','5000')
end try
begin catch
SELECT 
   ERROR_NUMBER() AS ErrorNumber
   ,ERROR_MESSAGE() AS ErrorMessage;
end catch

It's always a best Practise to write you TSQL code using Try and Catch Block so that your code will not stop in between if an error Occurs instead of that it will show some Custom or an Error message. 





Union vs Union All in SQL

Union vs Union All in SQL

In many situation you want to show data of  two or more tables in a single Select Statement 
Like You have two table Employee1 and Employee2
create table Employee1
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee1 values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000')

select * from Employee1

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000

create table Employee2
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000'),('arun','9500'),('akash','10500')

select * from Employee2

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000
6 arun        9000
5 akash      10500


Now you want to merge all the name ,salary present in both the Tables
for this use Union All 

--All  Rows from Table Employee1 and Employee2

select * from Employee1
union all
select * from Employee2


Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj         8000
4 vijay         9000
5 suresh 10000
1 Amit          5000
2 Sumit 6000
3 Raj       8000
4 vijay           9000
5 suresh 10000
6 arun          9500
7 akash 10500


IF you want to Display Only Distinct Data in Both the Tables i.e. Means No reapeated Rows 
then Use Union

--All distinct Row from Table Employee1 and Employee2
Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay          9000
5 suresh 10000
6 arun           9500
7 akash 10500

Performance wise Union All  Operator is Fast when there are large no. of Records
The Union Operators Scans both the Table matches the record for uniqueness and returns distinct Records which slow down the execution time when records are very large in Numbers
,whereas Union All will fetch the Datawithout looking for distinct record.

Note: While Using Union or UnionALL no. of columns in the select statement should be Same Secondly the Column Names by default  will be the First query column Names.




Assigning Values of Select Statement to a Variable in SQL

Assigning Value of Select Statement to a Variable in SQL

You often have a requirement like you have to set a  value to a variable to Perform 
some operation based on that value to explain it in a more better way 
I am creating a table

--Create a Table for Demo Purpose

create table Projects
(
ProjectName nvarchar(50),
ResourceName nvarchar(50),
Hours int,
Cost float
)


insert into Projects values('ProjA',1,8,3000),('ProjA',2,7,7000),('ProjA',1,3,3000),('ProjB',4,8,3700),('ProjB',1,5,3800),('Projc',1,5,3800),('ProjD',1,5,10,000)

select * from Projects

Now You want to store value of Project in a variable name @projectname   which matches the condition where cost =10000 to perform operation like updation cost adding 3000 to cost of that project

--use declare to declare a variable next datatype of variable


declare @projectname nvarchar(50)

select @projectname=projectname from projects where cost =10000

select @projectname 



Output ProjD



Now you want to add 3000 to cost to ProjD





declare @projectname nvarchar(50)
select @projectname=projectname from projects-- where cost =10000
select @projectname 
update Projects  set cost =cost+3000 where projectname=@projectname  
select * from projects where projectname=@projectname



ProjectName ResourceName Hours Cost
ProjD                  1             5              13000

In the above code it will take the Project name where cost =10000 
Update value to 13000  of the project assigned in the @projectname variable

Other way of assiging value to variable

declare @projectname nvarchar(50)
set @projectname=(select projectname from projects where cost =10000)
select @projectname 

Output ProjD

If you want to assign two or more value to two variable 

declare @projectname nvarchar(50)
declare @resourcename nvarchar(50)
select @projectname=projectname,@resourcename=resourcename  from projects where cost =13000
select @projectname ,@resourcename

Output 
ProjD ,1

Imp thing to keep in Mind with Variable

1- if the where clause has more than one Rows while assigning value to a variable it will take the value of First Row
Suppose ProjA and ProjD has same cost 13000
then it will take first row value which is ProjA
leaving Second Row  i.e Proj D Values 

2-If you do not specify any where condition to select clause it will Take the Value of Last Row
like 

declare @projectname nvarchar(50)

select @projectname =projectname from projects

select @projectname

Output 
ProjD 

This will take last Row ProjectName  value which  is Project D

NOTE: Keep in mind that while assigning Value to a variable in Select statement you cannot perform Data Retrieval operation means there should be only those column name whose values you are retrieving if you will include other columns in that query it will throw an Error.
To check run this query



declare @projectname nvarchar(50)
select @projectname =projectname,resourcename from projects

Error

Msg 141, Level 15, State 1, Line 3
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.


The Reason is you have added a ResourceName column in the query which is not assigning value to any variable. 







Cascading of Parameters in SSRS

Cascading of  Parameters in SSRS

In many Reports you have a requirement like you want to display report parameter based on other 
Report paramters
Let me Explain through Example

--Create a Table for Demo Purpose

create table Projects
(
ProjectName nvarchar(50),
ResourceName nvarchar(50),
Hours int,
Cost float
)

insert into Projects values('ProjA',1,8,3000),('ProjA',2,7,7000),('ProjA',1,3,3000),('ProjB',4,8,3700),('ProjB',1,5,3800),('Projc',1,5,3800)

select * from Projects

You want to display in your report how many Resources have worked in a Project for how many Hours
You have two Parameters in Your Report
1-Project Name
2-Resources

Now You want that whenever user Preview a Report he should select the Project Name 
Select Project Name will automatiically Popup the Resources working for that project 
Suppose  a User Select Project A
Then in Resources filter it will show all the Resources working on Project A...
Means the Report will filter Data Based on Resources working for a Project

Creating dataset for ProjectName

For this first create a Dataset -
DSTProjectNames
--That will Fetch all Project name

select projectname from Projects
--This will Display Name Like 
Proj A
Proj B
Proj C
click ok

Now add a Parameter for ProjectName

-Go to Parameters
-Right Click
-Add parameter
-ProjectName
-Allow Multiple Values Checked
-Available Values
-Check Radio Button -Get Values from a Query
-Dataset-DSTProjectNames
-Value field-ProjectName
-Display field-ProjectName
click ok


Creating Dataset for ResourceName

Now For Resource Name
create a Dataset-DSTResourceName
In Query-

select resourcename,projectname from projects 

Go to Dataset properties of DSTResourceName
Filter
ADD-ResourceName
Operator-In
Value-Double click fx sign-ADD your Parameter-ProjectName
click ok


Creating Parameters for ResourceName

-Go to Parameters
-Right Click
-Add parameter
-ResourceName
-Allow Multiple Values Checked
-Available Values
-Check Radio Button -Get Values from a Query
-Dataset-DSTResourceName
-Value field-ResourceName
-Display field-ResourceName
click ok


Now in your Main Dataset
You want to filter your Report Based on ResourceName
-Create Dataset for Main Report

Select projectname,resourcename,cost, hours from projectname
where resourcename in (@Resourcename)

This @Resourcename is your parameter that will filter your Report Based on ResourcesName
Click ok

Now preview the report

Try to click on ResourceName parameter without selecting ProjectName
It will Not allow you to click 

Select ProjectName from your ProjectName Parameter
-Automatiically ResourceName parameter will show the Values
Select ResourcesName based on which you filter the Main Report
Click View Report

Your Report will work properly.





Running Value Function in SSRS

Running Value Function in SSRS

In many Reports you want to display running sum like

Suppose you have a column Hours in your Report and in the Next column of your report you want to 
show running total of Hours like Below

Hours  Total Hours
8                8
10              18
20              38
30               68  
40              108

For this add a new column in your table Name it according to your Requirement in my case i have given it Total Hours

Select the Text Box Under your Column Name
Right Click -Expression-


--Write Below Expression
=RunningValue(Fields!Hours.Value, Sum, Nothing)

Preview the Report You will get the above output

The Running Function will take the value Sum it if no value is there it will do nothing.

Note: The above example is for Sum you can perform Other Examples also using this Function.




Where Conditon with Union or Union ALL in SQL

Where Conditon with Union or Union ALL in SQL

This Post is about how to use where conditon with Union and Union All operator

I have a query which uses Union all.

Below two queries are working fine 

select Col1,Col2 from table1
Union all
select Col1,Col2 from table2

--or for union

select Col1,Col2 from table1
Union 
select Col1,Col2 from table2

Now if you want that from table 1 it will show only that data where col is not null and from column 2 you want to show data where col2 >10
for this you cannot write query like this

select Col1,Col2 from table1
Union all 
select Col1,Col2 from table2
where table1.col is not null and table2.col2>10

this will throw an error 
Msg 207, Level 16, State 1, Line 4

Invalid column name table1.col

 In order to apply a where clause on the result set to column which are not the part of select clause.

Below is the solution

--Note Column Col from table1 is not in select column list
select Col1,Col2 from table1
where col is not null
Union all 
select Col1,Col2 from table2

table2.col2>10

-- for union

select Col1,Col2 from table1
where col is not null
Union 
select Col1,Col2 from table2

table2.col2>10


In case you want to filter complete union query then put the  complete union query inside a CTE or Derived Table.

--Using Derived table


Select * from 
(select Col1,Col2 from table1
Union all 
selection Col1,Col2 from table2)x


where x.col is not null and x.col2>10


--Using CTE

with x as
(select Col1,Col2 from table1
Union all 
selection Col1,Col2 from table2
)
select * from x where x.col is not null and x.col2>10






Removing Border Style of Tablix due to Overlapping in SSRS

Removing Border Style of Tablix due to Overlapping in SSRS

Today i face a problem while creating a ssrs report the border of table was not proper  Istill belive it might be a  comman problem to many developer   today i will tell you the solution so that it will save your time.

Below is the Screen Shot of Report where i was facing Problem

If you see the above report the First line above first row is Dark then other border lines of table
i tried to remove the textboxes border but still problem was there 
As it was only line who was comming Dark in the Report .
So I look properly on the report the Reason why firstborder  line was coming dark as the Text Boxes in the First row already have Border Property Solid and again in the Tablix properties the Border property was Solid 
So both first rows text boxes and tablix border was overlappign resulting table border thicker and Darker.
than others Borders line.

Solution -Select your tablix properties Border Go to Border Style Make it None or Default Once there will be no border for the Tablix so it will take Border Line of Text Box only 


Now you can See that there is no dark line over the First Row.

The Reason of blogging on this issue was that in order to identify why the First line was Dark as compared to others border line it took me 1 hour to identify the issue . So , I though may be there are others people also who might have on in future will face this kind of this so this blog will help them to provide the Solution.

Select * Into Statement in SQL

Select * Into Statement  in SQL


Select * or Select Columns Name Create a Target Table with the query you specified Mostly Use when you want to create a copy of a table or you want to insert the Output of a query into a Table
Let me Explain Through an Example
--creates a table
create table Employee
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000')

select * from Employee

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000

Now you want to copy this Employee table into a New Table CopyEmployee
for this You have to use Select * into

select * into CopyEmployee from Employee

Output

Empid EmpName EmpSalary
1 Amit         5000
2 Sumit 6000
3 Raj        8000
4 vijay        9000
5 suresh     10000

Now you want to put some result into a new table mean after joining table employee and copyemployee we want the result set in MergeEmployee Table for this

Select c.Empid as CEmpId,E.EmpId,C.EmpName as CEmpName,E.EmpName into MergeEmployee from employee e join
copyemployee c on e.empid=c.empid

select * from MergeEmployee 

Output


CEmpId EmpId CEmpName EmpName

1 1                 Amit                    Amit

2 2               Sumit                   Sumit
3 3               Raj                Raj
4 4               vijay               vijay
5 5               suresh     suresh

The Reason why i used  column alias because a table cannot have two column with same name in order to differentiate the column i used Column Alias

Note:Select into statement will copy the data only not keys,constraints and other things.