Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Friday, March 22, 2013

Add RowNumber Column in Table


Hello I have a Table with column PageId and PageName.Now i want add one more column Rownumber while selecting data.

So we can use the following querry.

 WITH tempTable as
  (
    select ROW_NUMBER() Over(order by PageId) As RowNumber,* from tblPageInfo
  )
  select * from tempTable


This will list three column RowNumber,PageId,PageName

Wednesday, September 26, 2012

Find Current Year Start Date and End Date in SQL?


select  DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)'Start Date ',
DATEADD(dd,-1,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,getdate())+1,0))) 'End Date'


Output


Start Date                          End Date
2012-01-01 00:00:00.000 2012-12-31 00:00:00.000


Find Current QUARTER Start Date and End Date in SQL

SELECT  DATEADD(qq, DATEDIFF(qq, 0, GETDATE()),  0)'Start Date',DATEADD(qq, DATEDIFF(qq, - 1, GETDATE()), - 1)'End Date'


Output:

Start Date                                 End Date
2012-07-01 00:00:00.000 2012-09-30 00:00:00.000

Tuesday, August 7, 2012

Crosstab queries using PIVOT in SQL Server

Problem

In SQL Server 2000 there was not a simple way to create cross-tab queries, but a new option in SQL Server 2005 has made this a bit easier. We took a look at how to create cross-tab queries in SQL Server 2000 in this previous tip and in this tip we will look at this new feature in SQL Server 2005 to allow you produce cross-tab results.

Solution

With SQL Server 2005 a lot of new features have been introduced. One of these new features is PIVOT.  What this allows you to do is to turn query results on their side, so instead of having results listed down like the listing below, you have results listed across.
SalesPersonProductSalesAmount
BobPickles$100.00
SueOranges$50.00
BobPickles$25.00
BobOranges$300.00
SueOranges$500.00
With a straight query the query results would be listed down, but the ideal solution would be to list the Products across the top for each SalesPerson, such as the following:
SalesPersonOrangesPickles
Bob$300.00$125.00
Sue$550.00
To use PIVOT you need to understand the data and how you want the data displayed.  First you have the data rows, such as SalesPerson and the columns, such as the Products and then the values to display for each cross section.  Here is a simple query that allows us to pull the cross-tab results.
SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
FROM
(SELECT SalesPerson, Product, SalesAmount
FROM ProductSales ) ps
PIVOT
(
SUM (SalesAmount)
FOR Product IN
( [Oranges], [Pickles])
) AS pvt
So how does this work?
There are three pieces that need to be understood in order to construct the query.
  • (1) The SELECT statement
    • SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
    • This portion of the query selects the three columns for the final result set (SalesPerson, Oranges, Pickles)

  • (2) The query that pulls the raw data to be prepared
    • (SELECT SalesPerson, Product, SalesAmount FROM ProductSales) ps
    • This query pulls all the rows of data that we need to create the cross-tab results.  The (ps) after the query is creating a temporary table of the results that can then be used to satisfy the query for step 1.

  • (3) The PIVOT expression
    • PIVOT (SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt
    • This query does the actual summarization and puts the results into a temporary table called pvt
Another key thing to notice in here is the use of the square brackets [ ] around the column names in both the SELECT in part (1) and the IN in part (3).  These are key, because the pivot operation is treating the values in these columns as column names and this is how the breaking and grouping is done to display the data.

Monday, July 30, 2012

How to format datetime & date in Sql ?

Introduction:

                  Lets see one by one with Example.

SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)
                                        – Jul  30 2012 11:01AM          
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 30/07/2012                  
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2012.30.07           
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) – dd mon yyyy
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy
SELECT convert(varchar, getdate(), 108) – hh:mm:ss
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        – Oct  2 2012 11:02:44:013AM   
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) – yyyymmdd
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm
                                        – 02 Oct 2012 11:02:07:577     
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm
                                        – 2012-30-07T10:52:47.513
– SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy

Saturday, July 28, 2012

How to Find day,week,year,month difference between two Dates in sql?

Introduction
             Here I am going to Explain you about how to Find the Difference of day,week,year,month between two dates in sql.

Lets create one table called OrderDetails
Now Lets How Find the difference  Of days,week,year,month with the current date.

select DATEDIFF(day,OrderDate,GETDATE()) As Numberofdays,DATEDIFF(week,OrderDate,GETDATE()) AS NumberofWeek,
DATEDIFF(Month,OrderDate,GETDATE()) As NumberofWeek,DATEDIFF(year,OrderDate,GETDATE()) As NumberofYear
 from OrderDetails


Here GetDate() will return the current Date.
First parameter of DATEDIFF() define what you want to find day,week,month or year.
and second and third parameter define to which you have to find the difference.

Now out put of the above query will be.


Same you can also Find the diffrence of Hour, minute,second and  millisecond .just you have to place this into first Parameter of DATEDIFF().

Wednesday, July 25, 2012

How to return the date part and time part from a SQL Server datetime datatype?

Introduction
                I am showing you how to Extract the date and Time from the current Date Time.

SELECT SUBSTRING(CONVERT(varchar(24), GetDate(), 121), 0, 11) as 'Date'

Date
2012-07-25

select SUBSTRING(CONVERT(varchar(24),GetDate(),121),12,12) as 'Time'

Time
01:45:43.133

If you want to Convert time to AM and PM Format then use Following querry

SELECT substring(convert(varchar(20), GetDate(), 9), 13, 5) + ' ' + substring(convert(varchar(30), GetDate(), 9), 25, 2) 'Time'

Time
1:45 AM

Tuesday, July 24, 2012

Find Current week start Date and End Date in SQL


Introduction:


                  Today I am going to Explain you how to Find Current Week start date and last date of current week.

SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) as 'StartCurrentweek',DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)+6 as 'EndCurrentWeek'

The Output is:
StartCurrentweek                  EndCurrentWeek
2012-07-23 00:00:00.000 2012-07-29 00:00:00.000

Sunday, July 15, 2012

Pivot Table in SQL.

Introduction:
                   Today I am going to show you how to use the Pivot Table in Sql.

This Pivot table is mainly used for the converting the row into column and then you can apply the aggregate function in the pivot table.

 Lets see the Example.


First lets create the table and insert the data into the table.


CREATE TABLE tblPivot
(
        colA nvarchar(500),
        colB nvarchar(500),
        colC int
)

INSERT INTO tblPivot  VALUES('A', 'X', 1)
INSERT INTO tblPivot  VALUES('A', 'Y', 2)
INSERT INTO tblPivot  VALUES('A', 'Z', 3)
INSERT INTO tblPivot  VALUES('A', 'X', 4)
INSERT INTO tblPivot  VALUES('A', 'Y', 5)
INSERT INTO tblPivot  VALUES('B', 'Z', 6)
INSERT INTO tblPivot  VALUES('B', 'X', 7)
INSERT INTO tblPivot  VALUES('B', 'Y', 8)
INSERT INTO tblPivot  VALUES('B', 'Z', 9)
INSERT INTO tblPivot  VALUES('C', 'X', 10)
INSERT INTO tblPivot  VALUES('C', 'Y', 11)
INSERT INTO tblPivot  VALUES('C', 'Z', 12)

select * from tblPivot


Now lets apply the Pivot Querry.


DECLARE @columns nvarchar(max)
SELECT
        @columns =
        STUFF
        (
                (
                        SELECT DISTINCT
                                ', [' + colB + ']'
                        FROM
                                tblPivot
                        FOR XML PATH('')
                ), 1, 1, ''
        )

EXEC
('
        SELECT
                *
        FROM
                (
                        SELECT
                                colA,
                                colB,
                                colC
                        FROM
                                tblPivot
                ) DATA
                PIVOT
                (
                        SUM(DATA.colC)
                FOR
                        colB
                        IN
                        (
                                ' + @columns + '
                        )
                ) PVT
')


and then see the Output
colA   X     Y     Z

A 5 7      3
B 7 8 15
C 10 11    12



If you close Look at the above querry then you can see the  I convert the colB data values into  Column and then i just apply the sum of it.


Thursday, June 14, 2012

How to exchange the two word of one column data using sql.

Introduction:
                     Here I am going to discussion about how to exchange the word of one column data using sql.

Some days back i had one Problem arise where i need to exchange the word of column data.In actual seniorio is like this ...In one table Users one column name Full Name is there where "FirstName LastName" stored but while displaying data I have to display "LastName FirstName".In this seniorio i have to apply the below querry to get the results.

The Users Table is Like this.



Now Apply below Querry.

Select SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50) + ' ' + SUBSTRING(FullName,0,CHARINDEX(' ',FullName,0)) as "LastName-FirstName" from  Users

Here i used the Substring where first substring will fetch the second word(LastName) and the second substring will fetch the first word(FirstName) and then i have concat it  both and name the column name "LastName-FirstName".

SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50)=CHARINDEX(' ',FullName) will find the string after space.means second word to end of string

CHARINDEX(' ',FullName,0)=this one string will start from index 0 to space will found means First word


The Output will be 


Wednesday, June 6, 2012

Returning ID from insert query in C#

Intoduction:
         I am going to explain how to return the Id after Inserting the data into table.

There may be many occassion comes where you need to use the Id of data after inserting the values into table.If you look at my post Explained in http://aspdotnetbank-kartik.blogspot.in/2012/05/how-to-create-webservice-and-how-can-we.html there is one Table called Office in that Post.so first you Create a Table(Office)  from that Post.but Be Remeber that OfficeId is Primary Key and also Auto Increment Value.

Now Lets Look at .aspx page

<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblOfficeName" runat="server" Text="Office Name"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtOfficeName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblCity" runat="server" Text="City"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblCountry" runat="server" Text="Country"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
                    <asp:Label ID="lblId" Text="ID=" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>

Now .aspx.cs Page write code in button Save Click Event.

  protected void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            con.Open();
            string s = "insert into Office values('" + txtOfficeName.Text + "','" + txtCity.Text + "','" + txtCountry.Text + "')";
            SqlCommand cmd = new SqlCommand(s, con);
            cmd.ExecuteNonQuery();
            SqlCommand idCMD = new SqlCommand("SELECT SCOPE_IDENTITY(); ", con);
            // Retrieve the identity value and store it in the CategoryID column.
            int newID = Convert.ToInt16(idCMD.ExecuteScalar());
            lblId.Text += newID;
        }

Now If you Look at the code I have used SqlCommand idCMD = new SqlCommand("SELECT SCOPE_IDENTITY(); ", con); It Just returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.


You can also use the Select Ident_Current(TableName);  and SELECT @@IDENTITY; in Place Of  SELECT SCOPE_IDENTITY();  from above example.

Means There are three way we can achieve the Id.Lets disccuss about this

Select Ident_Current(TableName);  For ex. Select Ident_Current('Office');

SELECT @@IDENTITY;

SELECT SCOPE_IDENTITY();

SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Download Source Code from here
Download

Now If you are using Linq to insert the Data then Its really Easy....

Office record = new Office();
record.OfficeName = "KP";
record.City="Ahmedabad";
record.Country="India";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
lblId.Text +=record.OfficeId

Monday, June 4, 2012

How do I find a value anywhere in a SQL Server Database?

Introduction

           This is really nice stuff and will get the useful at any time to anybody.I was at this situation where I want to find particular data but i dont know where this data reside means in which Table and in which column this data was there.At that Time i got this solution.I hope that it might help you.


I am posting on SP in which it searches all the columns of all tables in a given database and then Find the Particular Data.


 ALTER PROC [dbo].[SearchAllTables]
(
    @SearchText nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchText2 nvarchar(110)
SET  @TableName = ''
SET @SearchText2 = QUOTENAME('%' + @SearchText + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchText2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM @Results
END

Saturday, May 19, 2012

Delete Duplicate Rows From Table....


In this Article I will explain you about how to delete Duplicate rows from Table

Our Table does not contain any primary key column because of that it contains duplicate records that would be like this

Now just Run this Querry 

WITH tempTable as
(
select ROW_NUMBER() Over(partition by Name,Class order by Name) As RowNumber,* from ClassData
)
select * from temptable

OutPut Of this Querry will be 
If you observe above table I added another column RowNumber this column is used to know which record contains duplicate values based on rows with RowNumber greater than 1.  

Now we want to get the records which contains unique value from datatable for that we need to write the query like this


WITH tempTable as
(
select ROW_NUMBER() Over(partition by Name,Class order by Name) As RowNumber,* from ClassData
)
delete from temptable where RowNumber>1
select * from ClassData;

When you Run this Querry OutPut will be like this......


How to Get List of Columns Name,Data types of Table


Here I am explained you how to get the List of Columns and their datatypes from particular Table using SQL.

For Example i have a Table Office.write a querry


USE master
GO
SELECT column_name 'Column Name',
data_type 'Data Type',
character_maximum_length 'Maximum Length'
FROM information_schema.columns
WHERE table_name = 'Office'

where master=Database Name ,'Office' is a Table Name

After run this Querry you will get


Monday, April 30, 2012

What is the difference between Union and Union All Operator?

SQL UNION Operator:


The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

SQL UNION Syntax

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

SQL UNION ALL Syntax

SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.

SQL UNION Example

Look at the following tables:

"Employees_Norway":

E_IDE_Name
01Hansen, Ola
02Svendson, Tove
03Svendson, Stephen
04Pettersen, Kari

"Employees_USA":

E_IDE_Name
01Turner, Sally
02Kent, Clark
03Svendson, Stephen
04Scott, Stephen

Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:

SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA

The result-set will look like this:

E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.

SQL UNION ALL Example

Now we want to list all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA

Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen

The main difference between Union and Union ALL operator is

Union operator will return distinct values but Union ALL returns all the values including duplicate values.

Thursday, April 5, 2012

Difference between VARCHAR and NVARCHAR

The data type Varchar and Nvarchar are the sql server data types, both will used to store the string values.

The abbreviation for Varchar is Variable Length character String.
The abbreviation of Nvarchar is uNicode Variable Length character String.

The Varchar allocates single byte for a character. So can be used to store for 8000 characters in this datatype.

The NVarchar allocates two bytes for a character. Because this Nvarchar type allows to store the special characters. So can be used to store for 4000 characters in this types.

If you want to store more length of uNicode string, the you have to go for the TEXT and NTEXT data types. These are the BLOB( Binary Large Objects) datatypes.

Use Varchar and Nvarchar instead of TEXT and NTEXT as regular. The the later datatypes in unavoidable times.
 

Wednesday, April 4, 2012

SQL Server Reset identity column value of table

Introduction: 
In this article I will explain how to reset identity column value of table in in 
SQL server.

Description:
After set identity property on particular column(StudentId) I inserted few records in Student table and that value(StudentId) automatically increase whenever I inserted data that would be like this.Here I have inserted some Name of students.



Now I am Going to deleted all existing records and then tried to insert new records in table.Now if you can see that identity column value starting from previous increased value Ex: Above table contains 5 records after delete all the records if I insert new record StudentId value will start from 6.
To reset identity column value and start value from “1” during insert new records we need to write query to reset identity column value. Check below Query

DBCC CHECKIDENT (Table_Name, RESEED, New_Reseed_Value) where
Table_Name is name of your identity column table

RESEED specifies that the current identity value should be changed.

New_Reseed_Value is the new value to use as the current value of the identity column.   
  
EX: DBCC CHECKIDENT ('Student', RESEED, 0)
Once we run the above query it will reset the identity column in Student table and starts identity column value from “1”