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.

Friday, June 7, 2013

DROP multiple tables using single DROP statement

We know that how to drop a table. But we can also drop multiple tables using only single drop statement. How? Let see using the below example:

Just create multiple tables like:

CREATE TABLE t1(ID1 INT)
CREATE TABLE t2(ID2 INT)
CREATE TABLE t3(ID3 INT)

Try to select the table data to confirm that tables are created successfully by:

SELECT * FROM t1
SELECT * FROM t2
SELECT * FROM t3

Tables are created, Now we are going to drop those tables using single drop statement as below:

DROP TABLE t1,t2,t3

That’s work perfectly..





Friday, May 31, 2013

Insert default value for newly adding column in existing records in table in SQL Server.

Here we see how we insert default values in newly added column in table which already has some records in it.

Sometime we are in situation that we need to add new column and we need to assign default property to that column. If the table in which we add new column is empty then we don’t have an issue to set default values but if that table already having some records and we are adding new column with default value then either we need to be empty the table or update the records with default values.
Now in this case if there is lots of record in table then it is not easy to do this. But we have one simple way to come out of this very easily.

Simply create one table with two columns, insert some records into it:

CREATE TABLE TestTable
(
      ID INT,
      Name VARCHAR(10)
)
INSERT INTO TestTable
VALUES(1,'PP'),(2,'AA')

SELECT * FROM TestTable

Output:
ID
Name
1
PP
2
AA


Now we are adding new column with default values in existing records using:

ALTER TABLE TestTable
ADD newColumn BIT DEFAULT(0) WITH VALUES

SELECT * FROM TestTable

Output:
ID
Name
newColumn
1
PP
0
2
AA
0


Thursday, March 7, 2013

Display count for number of column in table with non zero values for each rows


declare @t table (ID INT IDENTITY(1,1),a int,b int,c int,d int)

insert into @t
values(1,0,0,0),(0,1,0,0),(1,2,0,0),(1,2,3,4),(1,2,3,0)

;with cte as
(
select * from @t
unpivot
(colvalue for colname in(a,b,c,d)) unpvt
)

select t.*,cnt from @t t
INNER JOIN (
select ID,COUNT(*) as cnt
from cte
WHERE colvalue > 0
GROUP BY ID
) x ON x.ID = t.ID

Output :