28.7.09

Case Statement in SQL Server

Interesting facts about Case statement in SQL Server
--- Creating the table Venkat
drop table venkat
create table venkat(id int, val int ,date datetime,nam varchar(10))
insert into venkat values(1,200,'3/2/2008','venka')
insert into venkat values(1,100,'10/2/2008','venk')
insert into venkat values(3,400,'10/2/2008','arun')
insert into venkat values(3,500,'10/4/2008','balu')
insert into venkat values(3,600,'10/4/2008','lakshmi')
insert into venkat values(3,700,'10/4/2008','santhi')

--------------------------------------------------------
select * from venkat
--------------------------------------------------------

Case statement is used to check the alternatives.
"If the value is this much, show it as this. Else show it as this."

--------------------------------------------------------
-- A simple select statement for you
select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

--------------------------------------------------------


--------------------------------------------------------
-- Complication in case statement
-- If i need to select two values based on one value. Then in this case, we need to write two case statement as below.
-- Instead of one case statement.
select id,
case
when val=100 then value ='One Hundred' and val = 'One'
when val=200 then value ='Two Hundred' and val = 'Two'
when val=400 then value ='Four Hundred' and val = 'Four'
when val=500 then value ='Five Hundred' and val = 'Five'
when val=600 then value ='Six Hundred' and val = 'Six'
when val=700 then value ='Seven Hundred' and val = 'Seven'
end

from venkat

--------------------------------------------------------
-- The above statement will throw error.
--------------------------------------------------------
select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end,
val=
case
when val=100 then 'One'
when val=200 then 'Two'
when val=400 then 'Four'
when val=500 then 'Five'
when val=600 then 'Six'
when val=700 then 'Seven'
end

from venkat

--------------------------------------------------------
-- My condition is to create a procedure with order by a column.
alter procedure venkatesanprabu_proc
(@options int)
as
begin

select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

order by
case
when @options=1 then id
when @options=2 then nam
end

end
--------------------------------------------------------
-- Case statement in Order by clause
--------------------------------------------------------
-- The above statement will throws an error.
-- An interesting fact in SQL Server is, we can't use different data type in the order by clause.
-- In the above statement, If it's option=1 then output will be order by id
-- Else if the option is equal to 2 then output will be order by nam.
--------------------------------------------------------
-- Here is the solution for the above problem. We need to use two case statement to resolve it.
--------------------------------------------------------
alter procedure venkatesanprabu_proc
(@options int)
as
begin

select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

order by
case
when @options=1 then id
end,
case
when @options=2 then nam
end

end
--------------------------------------------------------
exec venkatesanprabu_proc 1
exec venkatesanprabu_proc 2


--------------------------------------------------------

Thanks and Regards,
Venkatesan Prabu .J

Dependent Objects in SQL Server

Identifying Dependency or relative objects in SQL Server:

I have seen an interesting question in a SQL Server forum.

Scenario:

How to identify the dependency on an object?

Solution:

Sp_depends “Object_Name”

Sp_depends will give you all the dependent objects in the databse. Let’s see the implementation for this scenario.

--- Creating the table Venkat
drop table venkat
create table venkat(id int, val int ,date datetime)
insert into venkat values(1,200,'3/2/2008')
insert into venkat values(1,100,'10/2/2008')
insert into venkat values(3,400,'10/2/2008')
insert into venkat values(3,500,'10/4/2008')
insert into venkat values(3,600,'10/4/2008')
insert into venkat values(3,700,'10/4/2008')

-- Created a view "vw" to fetch records from the table "Venkat"
--------------------------------------------------------
create view vw
as
select * from venkat
--------------------------------------------------------
-- Created a procedure named VenkatesanPrabu_proc with the statement to fetch records from the view
--------------------------------------------------------
create procedure VenkatesanPrabu_proc
as begin
select * from vw
end
select * from vw
--------------------------------------------------------
sp_depends vw


Thanks and Regards,
Venkatesan Prabu .J

SSIS with oracle database

Oracle error while migrating the data from one Oracle database to another:

Fortunately, I got a chance to work with oracle database migration using SSIS. Below is a peculiar behaviour of SQL Server Integration services. I have connected OLE DB source and connected to a table. Dragged and dropped OLE DB Destination, I need to created new table, clicked “New”.

The syntax for the table got created with a create statement.

CREATE TABLE SQLGenerated (
"Type_RATES_ID" NUMERIC(12),
"Type_RATES_VN" NUMERIC(12),
"_TYPE_ID" NUMERIC(12),
"_RATE_TYPE" VARCHAR(2),
"LENDING_RATE" NUMERIC (7,6),
"HEDGING_MARGIN" NUMERIC (7,6),
"PROFIT_MARGIN" NUMERIC (7,6),
"COMMISSION" NUMERIC (7,6),
"ESTABLISHMENT_COST" NUMERIC (24,8),
"RATE_PERIOD" NUMERIC(6),
"DATE_FIX" DATETIME,
"MOD_USER_ID" NUMERIC(12),
"MOD_TIMESTAMP" DATETIME,
"_ID" NUMERIC(12),
"TOTAL_RATE" NUMERIC (7,6),
"FIXED_AMOUNT" NUMERIC (24,8),
"_AMOUNT" NUMERIC (24,8),
"_TYPE_RATE_DIFF" NUMERIC (7,6),
"MATURITY_DATE" DATETIME,
"_SWITCH_FLAG" NUMERIC(1)
)


On pressing “OK” button, am getting the below error.
ORA-00902: invalid datatype (OraOLEDB)





To resolve this issue,
1. I went back to oracle database
2. Created a script for the source database.
3. Copied the content and pasted it into the create table window.
4. Now it’s working fine.
The problem is due to the data type,


create table OracleGenerated
(
Type_RATES_ID NUMBER(12) not null,
Type_RATES_VN NUMBER(12) not null,
_TYPE_ID NUMBER(12) not null,
_RATE_TYPE CHAR(2),
LENDING_RATE NUMBER(7,6),
HEDGING_MARGIN NUMBER(7,6),
PROFIT_MARGIN NUMBER(7,6),
COMMISSION NUMBER(7,6),
ESTABLISHMENT_COST NUMBER(24,8),
RATE_PERIOD NUMBER(6),
DATE_FIX DATE,
MOD_USER_ID NUMBER(12),
MOD_TIMESTAMP DATE,
_ID NUMBER(12) not null,
TOTAL_RATE NUMBER(7,6),
FIXED_AMOUNT NUMBER(24,8),
_AMOUNT NUMBER(24,8) default 0 not null,
_TYPE_RATE_DIFF NUMBER(7,6) default 0 not null,
MATURITY_DATE DATE,
_SWITCH_FLAG NUMBER(1) default 0,
)
The problem is due to the datatype “Datetime”. SQL Server is generating datetime but oracle is not supporting the same. In turn, we need to modify the data type to “date” type.

Thanks and Regards,

Venkatesan Prabu .J

General options in SQL Server

General tools options in SQL Server:

Contolling the SQL Server editor window in SQL Server Management studio.

Goto Tools->Options-> Query execution->General, we are having lot of options.

1. Set Rowcount – This option is used to restrict the result set returned by the text editor.
Considering am having lakhs of records and I need to restrict the number of records returned, we can specify the same. It’s equivalent to the TOP keyword. “0” indicates that, there will be unlimited rows (or) no restrictions in the number of records fetched.


2. Set Textsize – This option is used to restrict the size of the text to be returned in your text editor. Considering, am having a column of type “TEXT”, If I have given 10 as the bytes. The resultset will be restricted with only 10 bytes.

3. Execution time-Out : We can restrict the query execution time. How much time, the query should execute. If we have given 0 as the value, then its unlimited or no restriction. This is very useful in executing a query in production environment.

4. Batch separator: This is used to separate the batch statement. Grouping the queries.
Strange but interesting facts of the GO statement. Before this article, I thought like the go statement will commit the transactions. But after checking this, I got shocked. It’s not committing it. I have tried to rollback the statement. The entire process got roll backed.


begin transaction
go
insert into venkat values(3,700,'10/4/2008')
go
insert into venkat values(3,700,'10/4/2008')
rollback

So, GO statement in SQL Server is used only for separating the SQL statements and it doesn’t have any impact on the transactions handling.








Thanks and Regards,

Venkatesan Prabu .J

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