Wednesday, March 30, 2016

SQL Pivoting on multiple columns

We can create pivoting on multiple columns as below.

Query:


IF OBJECT_ID('tempdb..#tbl') IS NOT NULL BEGIN
       DROP TABLE #tbl
END

CREATE TABLE #tbl(
       Dt            DATE,
       Acnt   INT,
       BCnt   INT,
       CCnt   INT
)
DECLARE
       @coldata VARCHAR(500),
       @sql varchar(max)

INSERT INTO #tbl
VALUES('2016-01-01',10,20,30),
('2016-01-02',40,50,60)

select * from #tbl
SELECT @coldata = COALESCE(@coldata + '], [', '') + FORMAT(Dt, 'yyyy-MM-dd') FROM #tbl
ORDER BY dt desc

SELECT @coldata = '[' + @coldata +']'

SET @sql = 'SELECT Dt=col, ' + @coldata + '
              FROM
              ( SELECT FORMAT(Dt, ''yyyy-MM-dd'') AS Dt, col, value FROM #tbl
                CROSS APPLY
                (
                     SELECT ''Acnt'',cast(Acnt as varchar(10)) UNION ALL
                     SELECT ''BCnt'', cast(BCnt as varchar(10)) UNION ALL
                     SELECT ''CCnt'', cast(CCnt as varchar(10))
                ) c (col,value)
              ) d
              PIVOT
              (
              MAX(value) FOR Dt IN (' + @coldata + ')
              ) AS piv'

EXECUTE (@SQL);


IF OBJECT_ID('tempdb..#tbl') IS NOT NULL BEGIN
       DROP TABLE #tbl
END

Result:

Actual result



With Pivot



 

Thursday, August 8, 2013

How to Split the string value into different column value

We have split string and populate its value into rows. For example   “A, B, C” is split and converted into rows with single column value like:
            A
            B
            C

But how can we split the string and put their values in different columns. Suppose we have person name in single column and his name is separated using comma for first name, last name and middle name, we need to split that string from that column and need to populate all these three values in individual column.

It can be done using the REPLACE() and PARSENAME() SQL functions.

Here is the example that demonstrates the use of PARSE function for splitting the string values and put that into the different column values.

DECLARE @name NVARCHAR(100)
SET @name='FName,MName,LName'

Now we replace the comma value with “.”, that is require for parsing the string like array in C#.

Replace the string with “.” Instead “,” using:

SET @name=REPLACE(@name,',','.')

Now finally we parse the person name into different column values by PARSENAME() function.

SELECT
      PARSENAME(@name,3) FName,
      PARSENAME(@name,2) MName,
      PARSENAME(@name,1) LName


Execute the whole query and it gives the result as:


Thursday, June 20, 2013

Fetch data from remote server using OPENROWSET in SQL Server

We are fetching the data from table in database with in server or fetching data from different database with in server. But sometimes we require fetching data from different database which is not in same server but it is in different server.

For different database but with in same server we can get records easily by “.(dot)” like:

SELECT * FROM DatabaseName.Schema.Table

Now let see how we can get the records from table from database which is not in same server and it is situated at different server.

This can be possible by the Linked Server also. However if we do not want to create link server and need to get the data then we have option to use “OpenRowSet”.

There are three parameters use in OpenRowSet which are:
  • Provider
  • Server (IP Address) with credentials (username/password) and database
  • Query (which is going to be executed with that server’s database)

Here is the syntax use to get data by OpenRowSet

OPENROWSET('SQLNCLI','Server=serverIP;Uid=UserName;Pwd=password;Database=DBName;','SELECT * FROM tablename')

Before executing this query we need to set some option which is requires to run the OpenRowSet query.

Set this option:

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO;

sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO;

After setting these option run the below query with proper required details:

SELECT
      FS.*
FROM OPENROWSET('SQLNCLI','Server=serverIP;Uid=UserName;Pwd=password;Database=DBName;','SELECT * FROM tablename') AS FS;

This will get the records from table which is not on same server but from remote server which is created in database on given Server.

This way it works without creating Linked Server  or without using the Import/Export option which already given to export the data from one server to other server by specifying the source and destination.

We can import/export the data from one database server to other database server’s table by:

Right click on database >> Go to Task >> Go to Import/Export



Hope this helps…..

Wednesday, June 12, 2013

Allow saving changes that require table re-creation while changing table design

Sometimes we have a situation that we need to change design of table either changing the size of column or type of column or we need to add new column into the existing table.

If we are doing table changes through wizard and we face an issue sometimes that SQL doesn't allow us to save the changes and give the restriction message like saving changes is not permitted” because of either tables has data and it requires to be re created or something that not allowed with SQL rules.

See the below screen that comes when you change anything in table structure and trying to save. It not comes every time but sometimes it validates the table structure with internal mapping of type, constraints and data.

In above image we can see that it prevents to save table changes and gives the validation message that it needs to be recreated and the option to allow is not selected for this kind of message.

So here we should allow this by setting the option in SQL Server “Tool” menu.

Go to the Tool and then go to the Option, click on the Designer item in left tree then select the Table and Database Designer. We will get the right side some of the option as showing in to the below screen.


In above screen unchecked the “Prevent saving changes that require table re-creation” option and then click on OK.


After setting this option again try to save table structure changes, Now that saving permission message has been removed and it allow for the further changes.

Tuesday, June 11, 2013

Delete Vs Truncate in SQL Server

We will see in this post How delete and truncate will work with temp table.

We have use many times truncate and delete command with Database Table and it works perfectly. It will allow truncating the table if that table doesn't have any records or if it has records then that table must not have any reference with other table.
If the table has reference with other table then we can not truncate table without deleting or truncating the reference table records. But we can delete the records from the reference table.

Now here we see how the truncate and delete command works with the Temp Table and see the difference between them.

We will see with the below examples.

Truncate:

Create one temp table with an identity field like below:

CREATE TABLE #Test
(
      ID INT IDENTITY(1,1),
      Name VARCHAR(10)
)
Insert some recors into #Test Table


INSERT INTO #Test
VALUES('PP'),('AA')

See the output using:


SELECT * FROM #Test


Here you can see there two records are inserted with identity value. Now we are truncating the temp table and inserting again these records and sees what will happen.

It has truncated the table and also reset the identity value to its original seed.

Delete:

Now we delete the records from temp table instead truncate and then again insert the records into temp table and see what will happen.
Let see:

We can see in above result that after deleting the records it has next identity value in ID field and it will insert the next increment value into the ID field.

Remove the table after execution using this:

DROP TABLE #Test

So here we conclude that the Truncate command will delete the records from table and also reset the identity value if any field has an identity set and reset it to the original seed value. While Delete command just deletes the record from table and not resetting any value for identity column.

Check the size of database files in SQL Server

How can we check the size of particular database files like .ldf and .mdf?

We can check the size which is occupied by the database files using the sys.database_files view.

To check the size of database files .ldf and .mdf use the below query:


use databasename
GO

SELECT
       Name AS DatabaseName
      ,Physical_name AS DBPath
      ,(size * 8)/1024 AS SizeMB
FROM sys.database_files


Output:








Here it shows the Database file name with location of file and size in MB unit.

Sunday, June 9, 2013

Default character limit for VARCHAR DataType

We use many time even mostly VARCHAR DataType in SQL Server. But some time we get issue or confusion with the default limit or character size of VARCHAR datatype, and that comes to the logical error with your queries or in your compile code (Stored Procedure) when execute it and gives the wrong output.

We will see how it works when we do not define size with VARCHAR datatype and give us the unexpected output.

See the below two scenarios how VARCHAR datatype works with query:

Scenario 1:

1. VARCHAR datatype With Variable

--Varchar used with variable
DECLARE @a VARCHAR
SET @a = 'Paresh'
SELECT @a AS Value


Output:




Now here in this scenario we can see it gives output as only 1 character because when we use VARCHAR DataType with variable and not define any size it takes only single character size default.

Scenario 2:

2. VARCHAR datatype with Convert and Cast function

--Varchar used with CONVERT or CAST Fucntion
SELECT CONVERT(VARCHAR,'aaaaa bbbbbb cccccc dddddd eeeee ffffff ggggg hhhhhh') AS Value

SELECT CAST('aaaaa bbbbbb cccccc dddddd eeeee ffffff ggggg hhhhhh' AS VARCHAR) AS Value

Output:




Here we can see that when VARCHAR DataType use with Convert or Cast function then it takes the 30 character as default size for it and give the output with only 30 characters.
  
So here we need to keep in mind that when we use VARCHAR Datatype then MUST give the size whatever it requires as per the use.