29.10.09

Datediff function in sql server

Datediff function in SQL Server:

Datediff function is used to differentiate two different dates/month/year.
The syntax is,

Datediff(Month or day or year, Date1, Date2)

If needed, Date1 can be current date to get the desired values. Let's see some examples,

declare @val datetime
declare @val2 int
declare @val3 datetime
declare @val4 int
set @val='11/3/2009'
select @val2 = (datediff(month ,@val,getdate() ))-- + (@val1 *12) )
print @val2 -- The ouptut is -1
set @val3='11/3/2007'
select @val4= (datediff(month ,@val3,getdate() ))-- + (@val1 *12) )
print @val4 -- The ouptut is 23


Let's try with day difference,


declare @val datetime
declare @val2 int
declare @val3 datetime
declare @val4 int
set @val='11/3/2009'
select @val2 = (datediff(day ,@val,getdate() ))-- + (@val1 *12) )
print @val2 -- The ouptut is -4
set @val3='11/3/2007'
select @val4= (datediff(day ,@val3,getdate() ))-- + (@val1 *12) )
print @val4 -- The ouptut is 727


Thanks and Regards,
Venkatesan Prabu .J

28.10.09

Numeric datatype in SQL Server

Numeric datatype:

Numeric datatype is equivalent to the decimal datatype. Decimal (ANSI supported) is recent version of numeric datatype.
Numeric datatype will have be declared with a scale and precision.

Syntax:
variableName numeric(scale, precision)

Let's see some samples,

create table venkat (id numeric(1,3))

On executing the above command, am getting the below error.
Msg 183, Level 15, State 1, Line 1
The scale (3) for column 'id' must be within the range 0 to 1.


Reason for this SQL error:
The scale value should be bigger than the precision value. If we declare numeric (5,2). Then, the value will be 3 digits with 2 decimal points. (Example 456.45, 453.23)

So, the number followed with the numeric keyword should be bigger.

Lets try this,

create table venkat (id numeric(5,3))

Our table is created.
Happy Learning!!!

Thanks and Regards,
Venkatesan Prabu .J

26.10.09

Datatype conversion in SQL server (Float to Int)


Let's see an interesting article on data type conversion,
select 8.5

-- The output is 8.5


Using convert operator to convert a float value into an integer:
select convert(int,8.9)


The above statement will try to convert the value into a possible integer. An equivalent of floor function.


Floor and ceiling functions in SQL Server:
Floor function is used to get the lowest possible integer value from the given float value

select floor(8.9)
-- The output will be 8


Ceiling function is used to fetch the possible maximum value(next possible integer value) from the given float value.


select ceiling (8.9)
-- The output will be 9


select ceiling (8.4)
-- The output will be 9


Using Cast operator in the conversion process:


select cast (8.9 as int)


The above statement will try to cast the value into a possible integer. An equivalent to floor function.

Thanks and Regards,

Venkatesan Prabu .J

21.10.09

Sys.Index table in sql server

All about Sys. Indexes table:

Sys.Indexes table will list down all the indexes available in the database. In detail, it will list down the clustered indexes, Non-clustered indexes and heap.

Clustered indexes will restructure the entire data inside the table where as non clustered index will create a pointed inside the table.

On executing the below query,

select * from sys.indexes

The table will hold the name of the index/type of the index/fill factor/ its working nature /hold primary key/unique key etc..,

To find the disabled indexes:

select * from sys.indexes where is_disabled = 1

To find, whether the index holds primary key (Index created due to the primary key on the table)
select * from sys.indexes where is_primary_key=1

To find, whether the index holds unique key on the column:
select * from sys.indexes where is_unique_constraint=1

Thanks and Regards,

Venkatesan Prabu .J

Special symbols in the column names in sql server table

Usage of special characters and keywords as the column name:

It's obvious that, we used to use keywords or special characters in the column name. SQL Server won't permit us to use the same directly. In that case, they will provide an option (Brackets [ ]) to use it.

Let see our example,

create table venkattable(kg/m varchar(10))

Output:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '/'.



To resolve this issue, I have used brackets.

create table venkattable([kg/m] varchar(10))

Output:

Command(s) completed successfully.

Thanks and Regards,
Venkatesan Prabu .J

15.10.09

Identity usage across table in SQL Server

I have come up with an interesting topic of using IDENTITY option in SQL Server.

As you know, Identity option is used to create unique values in regular intervals. One of the forum person have asked an interview question like, "Is it possiblel to spawn the identity value across the tables. Since identity is table specific item. How can we acheieve it?"

Nice question right!!!! Let' see how to acheive it?

Option 1:
Create a primary key in the table 1 and refer this column in the other tables. Make the columns in other two tables as primary key.

Option 2:
Create a primary key in one table and refer the column in other two tables. Make the other two tabels column as unique non-clustered index column (or) unique clustered index column else add a unique constraints on the columns in the other table.

Thanks and Regards,
Venkatesan Prabu .J

13.10.09

Remote query timeout in SQL Server


Ocassionally, Application will throw Query timeout errors. Do we have analysed why its happening?



Remote query timeout is due to the following reasons,


1. Server performance is too slow due to large number of transactions. So, it couldn't allocate necessary resources for the current session.


2. Network issue.

3. May be a very long complex query which will take more time to execute.

In that case, we can set the option of remote query timout to infinite or we can increase the timings.




Cheers,
Venkatesan Prabu .J

Decode function in Oracle

Decode function in Oracle:
Decode is an oracle specific function which is equivalent to "IF else" function in SQL Server.

For example:

Am having a query in oracle
SELECT ID, decode(id, 1, 'Venkat', 2,'Arun', 'NoName')NAME FROM VenkatTable

The equivalent function in SQL Server is.


decode(id, 1, 'Venkat', 2,'Arun', 'NoName')NAME

->

IF ID = 1 THEN NAME ='Venkat'

ELSEIF ID=2 THEN NAME ='Arun'

ELSE NAME ='NoName'

Thanks and Regards,

Venkatesan Prabu .J

Script SQL Databases

Scripting SQL Server 2005 database:
This is one of an interesting topic which I like to cover it in my blog. How to script a SQL Server database?

Right click on the database -> Goto tasks -> Generate scripts

You will get a small window to generate SQL Server scripts.

On clicking next button, all the databses will be listed down.
In the next page, we will having an option to be taken while scripting your database.


On clicking next button, you will get the objects details. What are the objects to be considered in generating the script.

If we select "Stored procedure" in the above screen. We need to select the needed stored procedures.

If we have select the tables, then MS SQL will provide an option to select the tables from the list.

This is the final option which will tell you the format to store the scripts.
Whether we need to script it into a new window (or) file (or) in the clip board.

Click next-> followed by finish button will generate the scripts in SQL Server.

Below is the progress option to check the scripts generated.
Thanks and Regards,
Venkatesan Prabu .J

After update trigger in SQL Server

Trigger:
Triggers are automatic invocation of statements. It can be written based on the action (or) a response for the action (or) a preliminary step before the action.

Considering a scenario, I need to insert a record while updation happened in the table. In that case, we can write after update trigger (Below is an example). Similarly, we will be having after insert, for insert, for update triggers.

Below is a small code snippet to create a table + trigger,

create table venkat(id int, val varchar(20))
insert into venkat values(1,'Venkat1')
insert into venkat values(2,'Venkat2')
insert into venkat values(3,'Venkat3')
insert into venkat values(4,'Venkat4')
select * from venkat

create trigger upd_venkat on venkat
after updateas
begin
insert into venkat values(5,'Venkat5')
end

update venkat set id=6 where id=4

select * from venkat

Thanks and Regards,
Venkatesan Prabu .J

6.10.09

Finding text in the stored procedure

This article is one of an interesting article which will tell you a nice concept of searching a text inside the objects.

Scenario:
I want to fetch all the stored procedure which is using a specific table(Venkat_table). How to find it?
Below is the solution for the same,
-- Creating the table
drop table Venkat_Table
create table Venkat_Table(id int)
insert into Venkat_Table values(10)
insert into Venkat_Table values(20)
insert into Venkat_Table values(30)
select * from Venkat_Table


-- Creating the procedure
create procedure Venkat_proc
as
begin
select * from Venkat_Table
end


-- In SQL Server 2005, we will have sys.procedures which holds all the details of the procedure.-- Defintion of the the specific object will provide you the definition details of the object.

SELECT *
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Venkat_Table%'



-- In SQL Server 2000, we will have syscomments and sysobject. syscomments will hold the definition of the object. sysobjects will list downt the objects. Joining syscomments and sysobjects will retrieve the necessary object names.

Below is the query to fetch the same,

SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%Venkat_Table%'



This will give the object definition inturn it's an alternative for the sp_help text option in SQL Server.

SELECT OBJECT_DEFINITION (OBJECT_ID(N'Venkat_proc'))

Thanks and Regards,
Venkatesan Prabu .J
Happy Learning!!!

Schema Names in Oracle database

Listing the schema names in Oracle database:

For retrieving the schema names from the oracle database, we need to use dba_objects table.

select * from dba_objects

The above query will retrieve all the objects from the table. Below are some of the high level information.
Owner: Schema name
Object Name: Name of the object
Object_ID : Unique ID generated by the oracle database.
Object_type : Type of the object whether its a table/index/view or synonym
Created : creation time
Valid : Whether this object is valid or not?


Below is the query used to fetch all the schemas located in the oracle database.

select owner,count(owner) cnt from dba_objects group by owner

It includes all the system related schemas. This can be removed by using not in operator. Schema names like Oracle, Common, system, xdb etc.., were related to Oracle system related schemas.

Thanks and Regards,

Venkatesan Prabu .J

Happy Learning!!!

My T-SQL Gallery @code.msdn.microsoft


Created my own T-SQL Gallery in Microsoft site. Do visit the same and share your feedback,

http://code.msdn.microsoft.com/VenkatSQLSample/Thread/List.aspx

Thanks and Regards,
Venkatesan Prabu .J

SQL Server Interview questions - Part 1

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

What is SQL whats its uses and its component ?
The Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. It enable us to retrieve the data from based on our exact requirement. We will be given a flexibility to store the data in our own format.


The DML component of SQL comprises four basic statements:
* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables


What is DTS in SQL Server ?
Data Transformation Services is used to transfer the data from one source to our required destination. Considering am having some data in sql server and I need to transfer the data to Excel destination. Its highly possible with dialogue based tool called Data Transformation services. More customization can be achieved using SSIS. A specialized tool used to do such migration works.


What is the difference between SQL and Pl/Sql ?

Straight forward. SQL is a single statement to finish up our work.Considering, I need some data from a particular table. “Select * from table” will fetch the necessary information. Where as I need to do some row by row processing. In that case, we need to go for Procedural Logic / SQL.

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

Difference between primary key and Unique key?
Both constraints will share a common property called uniqueness. The data in the column should be unique. The basic difference is,
· Primary key won’t allow null value. Whereas, unique key will accept null value but only one null value.
· On creating primary key, it will automatically format the data inturn creates clustered index on the table. Whereas, this characteristics is not associated with unique key.
· Only one primary key can be created for the table. Any number of Unique key can be created for the table.

Select Statement in SQL Server

Select Statement in SQL Server

String Functions in sql server

String Functions in sql server
Substring/Len/replace/Ltrim/Rtrim

SQL Server Interview Question - Part 2

What is normalization?

Normalization is the basic concept used in designing a database. Its nothing but, an advise given to the database to have minimal repetition of data, highly structured, highly secured, easy to retrieve. In high level definition, the Process of organizing data into tables is referred to as normalization.


What is a stored procedure:
Stored procedures are precompiled T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. As, its precompiled statement, execution of Stored procedure is compatatively high when compared to an ordinary T-SQL statement.


What is the difference between UNION ALL Statement and UNION ?
The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION,the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

Example for Stored Procedure?
They are three kinds of stored procedures,1.System stored procedure – Start with sp_2. User defined stored procedure – SP created by the user.3. Extended stored procedure – SP used to invoke a process in the external systems.Example for system stored proceduresp_helpdb - Database and its propertiessp_who2 – Gives details about the current user connected to your system. sp_renamedb – Enable you to rename your database


What is a trigger?

Triggers are precompiled statements similar to Stored Procedure. It will automatically invoke for a particular operation. Triggers are basically used to implement business rules.


What is a view?
If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.


What is an Index?
When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.


What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL ServerClustered -

1. It will format the entire table, inturn physically sort the table.

2. Only one clustered index can be created for a table.

3. Data will be located in the leaf level.

4. By default, primary key will create clustered index on the table.

Non-Clustered Index

1. It wont touch the structure of the table.

2. It forms an index table as reference to the exact data.

3. A reference to the data will be located in the leaf level.

4. For a table, we can create 249 non clustered index.

Happy Learning!!!
Regards,
Venkatesan Prabu .J

SQL Interview question

Extent Vs Page?

Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.The size of the page is 8KB.

Eight consecutive pages will form an extent 8 * 8KB = 64KB.

Thus I/O level operation will be happening at pages level.The pages will hold a template information at the start of each page (header of the page).

They are,

1. page number,

2. page type,

3. the amount of free space on the page,

4. the allocation unit ID of the object that owns the page.

Extents will be classifed into two types,

1. Uniform extents

2. Mixed extents

Uniform Extents:It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.Mixed

Extents:Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Property of SQL Server :Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

Herecomes, our fragmentation and reindexing concepts.



Best Joke - Enjoy it

Best Joke - Enjoy it