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 :

Sunday, November 4, 2012

Remove non alphabetic character from string in SQL Server

Query to remove non alphabetic character from string in sql server:


DECLARE @str varchar(100) = 'Paresh@#$Patel#$!@#888'

SELECT CAST(
  (SELECT CASE
           WHEN SUBSTRING(@str, n, 1) LIKE '[A-Z]'
           THEN SUBSTRING(@str, n, 1)
           ELSE ''
          END
  FROM (SELECT number
        FROM master..spt_values
        WHERE type = 'P'
          AND number BETWEEN 1 AND 50) AS Number(n)
  WHERE n <= LEN(@str)
  FOR XML PATH('')) AS NVARCHAR(100))

Run this query you will get the output like :

PareshPatel