31.3.11

Case in Select statement in SQL Server

DROP TABLE VENKAT_TABLE GO CREATE TABLE VENKAT_TABLE(ID INT, NAME VARCHAR(100),MARKS INT) INSERT INTO VENKAT_TABLE VALUES (1,'VENKAT',20) INSERT INTO VENKAT_TABLE VALUES (2,'SUBA',80) INSERT INTO VENKAT_TABLE VALUES (3,'LAKSHMI',45) INSERT INTO VENKAT_TABLE VALUES (4,'SANTHI',70) SELECT ID, NAME, CASE WHEN MARKS >50 THEN 'GOOD' ELSE 'BAD' END AS RESULT FROM VENKAT_TABLE

Order of Execution of Select Statement

This article is not clearly displayed in this blog, I have posted the same article in my other blog too. http://www.c-sharpcorner.com/Blogs/4536/order-of-execution-of-select-statement.aspx One of my blog reader have asked a query on SQL Server query execution order. Thought of writing an article on the same. select * from Student where id< 5000 group by studentID having subjectid=10 order by student name Here is the order of execution for your select statement. FROM --> Which Primary table ON --> On which column to join JOIN -->With which table, you want to join WHERE --> what are the conditions to filter the record GROUP BY --> on what basis, you want to group. WITH CUBE or WITH ROLLUP --> Show the data in the form of knowledge cubes. HAVING --> Another filter criteria S ELECT --> Get the data DISTINCT --> Remove duplicates ORDER BY --> Display in this order TOP --> Display only this much. That's really awesome processing of your query. My only concern is, why we are grouping the data afterwards we are having another filter criteria like having. May be having can be placed front before grouping it. Anyway, I will put this question to Microsoft. For our example, select * from Student where id < 5000 group by studentID having subjectid=10 order by student name The order of execution is, from -->where --> group by -->having --> select -->; Order by Cheers, Venkatesan prabu .J http://venkattechnicalblog.blogspot.com/ http://www.kaashivinfotech.com/

Horizontal ruler in HTML

I happened to use HTML for my company website (http://www.kaashivinfotech.com/). During my design for segregating the content, I've used table row and table data with lines in the boundary like, OOps, it's a costliest work to do and it's not efficient way to give a break line between the contents.




On my random search, I found the horizontal ruler in my VS tool box. Awesome, Here is the one line code to achieve the same,




To provide colour to the ruler


To provide the size to the ruler. Here is an option




width - Indicates the length of the ruler

size - Indicates the thickness of the ruler.


Cheers,

Venkatesan Prabu .J

23.3.11

Combining two views in SQL Server

Let's talk about views in SQL Server. Views are nothing but virtual tables which covers the table in SQL Server.

Am creating two tables,


DROP TABLE VENKAT_TABLE
GO
CREATE TABLE VENKAT_TABLE(ID INT, NAME VARCHAR(100))
GO
INSERT INTO VENKAT_TABLE VALUES(1,'SUBA')
GO
INSERT INTO VENKAT_TABLE VALUES(1,'ARUN')
GO
DROP TABLE VENKAT_SECOND_TABLE
GO
CREATE TABLE VENKAT_SECOND_TABLE(ID INT, AGE INT)
GO
INSERT INTO VENKAT_SECOND_TABLE VALUES(1,20)
GO
INSERT INTO VENKAT_SECOND_TABLE VALUES(1,30)
GO

-- Now am creating the views for the tables.

-- Views are nothing but virtual table which is like a mask on the table. For security reasons, instead of allowing the user to access the tables directly we will use views.


CREATE VIEW VENKAT_VIEW
AS
SELECT * FROM VENKAT_TABLE
GO
CREATE VIEW VENKAT1_VIEW
AS
SELECT * FROM VENKAT_TABLE
GO
CREATE VIEW VENKAT_SECOND_VIEW
AS
SELECT * FROM VENKAT_SECOND_TABLE
GO

Joining two views

------------------------------------------------------------------------------------
SELECT V1. * FROM VENKAT_VIEW V1 INNER JOIN VENKAT_SECOND_VIEW V2
ON V1.ID=V2.ID

Merging the results sets of the view.

(For merging the result set, we can use union all or union operator)

------------------------------------------------------------------------------------
SELECT * FROM VENKAT1_VIEW UNION ALL
SELECT * FROM VENKAT_VIEW

Cheers,
Venkatesan Prabu .J
Head - http://www.kaashivinfotech.com/
http://venkattechnicalblog.blogspot.com/

22.3.11

Enable Backup compression in SQL Server

Backup compression is a very important feature introduced in SQL Server 2008. Using this technique, the daily backups from the server were compressed and lot of spaces were saved.

"Usually in production servers, DBA's /jobs will take the backup frequently. In least case, 1 backup per day. The file will be ended with *.bak". The size of the backup depends on the size of the database. To avoid more space for the backup's, Microsoft have introduced this backup compression technique." We will see more details on the new compression techniques in my future article.


Let's see how to enable the backup compression option in SQL Server.


USE master
GO
EXEC sp_configure 'backup compression default'
GO
EXEC sp_configure 'backup compression default', '1'
RECONFIGURE WITH OVERRIDE
GO
EXEC sp_configure 'backup compression default'
GO




Cheers,Venkatesan Prabu .J

Head - www.KaaShivinfotech.com

http://venkattechnicalblog.blogspot.com/

Get the description of the Collation settings

In my previous post, we have seen how to identify the collation settings in the server. The output which we got is not much clear to the normal users. That's why, Microsoft have introduced a built in function to identify the collation which can be understood by normal users.

The function name is sys.fn_helpcollations()

In my previous post, I got my collation setting for my server as, 'Latin1_General_CI_AI'. Below is the query to get the detailed description of the collation.

SELECT description FROM sys.fn_helpcollations() WHERE name = 'Latin1_General_CI_AI'

The output is,

Latin1-General, case-insensitive, accent-insensitive, kanatype-insensitive, width-insensitive

Kanatype - It's Japanese support data
Width - Width of the data is not considered.

Try your query like below to get the collation settings and their detailed description.

SELECT description FROM sys.fn_helpcollations() WHERE name = 'Latin1_General_CI_AI'

Cheers,
Venkatesan Prabu .J
Head - www.KaaShivinfotech.com
http://venkattechnicalblog.blogspot.com/

Identify the Collation settings of the server

Here is the handy query to identify the Collation settings on the Server.

SELECT SERVERPROPERTY('Collation')

The output is,

Latin1_General_CI_AI
It indicates my server will support Latin general language, with Case insensitivenss and Accent insensitiveness.

Cheers,
Venkatesan Prabu .J
Head - www.KaaShivinfotech.com
http://venkattechnicalblog.blogspot.com/

How to find Network Adapters available in your machine??

Option 1:
In Control panel, you can see the available network adapters.


Option 2:
Goto Control Panel -> Device Manager -> Network Adapter

Cheers,
Venkatesan Prabu .J
Managing Director - www.Kaashivinfotech.com

3.3.11

Accessing Text Box content

I have seen the below query in a popular forum. Thought of writing something on this. This is the below query,

Conversion failed when converting the varchar value 'System.Web.UI.WebControls.TextBox' to data type int.

I cant understand why it will occur,i insert the data regarding to the correct datatype only

The guy is trying to access the text box value and he want to convert the value to integer.

Guessing, he is trying to get the value 'System.Web.UI.WebControls.TextBox'. Error indicates, the guy is trying to access the textbox property instead of text box data. In turn you need to access the textbox content like textbox.text and after wards convert the same to integer.

Cheers,
Venkatesan Prabu .J
Head - www.KaaShivinfotech.com
http://venkattechnicalblog.blogspot.com/

Naming the Constraint in sql server

Dynamically naming the constraint:
Constraint is nothing but a condition placed on the column or object. Let's see a small example to create a Primary Key constraint.


CREATE TABLE SANTHOSH_TABLE (NAME VARCHAR(100),ID INT PRIMARY KEY,DOB DATETIME)

---- INSERT RECORDS INTO THE TABLE ----------
INSERT INTO SANTHOSH_TABLE VALUES('VENKAT',1,'1/1/2010')
INSERT INTO SANTHOSH_TABLE VALUES('LINGAM',2,'1/1/2009')
INSERT INTO SANTHOSH_TABLE VALUES('ILAM',3,'1/2/2010')
INSERT INTO SANTHOSH_TABLE VALUES('SANTHOSH',4,'1/3/2010')
INSERT INTO SANTHOSH_TABLE VALUES('SIVARAM',5,'1/4/2010')

SELECT * FROM SANTHOSH_TABLE


The Primary key constraint name is
PK__SANTHOSH__3214EC2762AFA012 which looks tougher to remember the name. This name is automatically generated by SQL Server. Can we have a specific name to the Constriant?

Below query will drop the constraint located in to your table.


--------- DROP CONSTRAINT ON THE TABLE
ALTER TABLE SANTHOSH_TABLE DROP CONSTRAINT PK__SANTHOSH__3214EC2762AFA012

Now, lets see how to name a constraint.


---- DROPPING THE TABLE------------
DROP TABLE SANTHOSH_TABLE


---- NAMING THE CONSTRAINTS EXPLICITLY------------
CREATE TABLE SANTHOSH_TABLE (NAME VARCHAR(100),ID INT ,DOB DATETIME,
CONSTRAINT PK_ID_SANTHOSH PRIMARY KEY (ID))

Now, you constraint name is PK_ID_SANTHOSH.

Happy Learning!!!

Cheers,

Venkatesan Prabu .J

2.3.11

Performance tuning Query

This is Dastagiri from hyderabad .I have two years experience in Database’s SQL Server 2005, MySql, ADS servers.But I dint not understand how to apply performance tuning for large time taking queries.Could you please send me any material or video links to me.


Thanks,
Dastagiri.

Sir,

Advising you to get some good books on performance tuning.

http://www.sql-server-performance.com/tips/performance_main.aspx

http://www.mssqltips.com/category.asp?catid=9

http://msdn.microsoft.com/en-us/library/ff647793.aspx

Here are some of the useful links to start your performance tuning with SQL Server

Cheers,
Venkatesan Prabu .J
www.Kaashivinfotech.com

Query on DateTime operations

Anyway, here is the tips to resolve the problem.

Not working:

select * from Production_Table WHERE [Rep_Code] IN ('117','118','146','147','148','701','702','704','705','706','707','709','710','711','712','713','202') and Rep_Type LIKE '6%' and CONVERT(VARCHAR(8),CONVERT(DATETIME,(Load_Date)),112) between '20110120' and '20110126'

Error message:
Server: Msg 242, Level 16, State 3, Line 1 The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

Working:

SELECT CONVERT(VARCHAR(8),CONVERT(DATETIME,(Load_Date)),112) FROM from Production_Table WHERE [Rep_Code] IN ('117','118','146','147','148','701','702','704','705','706','707','709','710','711','712','713','202') and Rep_Type LIKE '6%'


So, the loop hole is with the between operator.

Step 1: Most probably, the issue is with the data. It’s a data issue.
Step 2: Check your objects whether any changes happened on the column.
Step 3: Check for the data, any manual entry to add special symbols (Single quotes) may happen.
Step 4: Use a loop operations to identify the exact error data or use top operator to identify it manually.

All the best and sorry for my delay response.

Cheers,
Venkatesan Prabu .J
Managing Director – KaaShiv Info Tech

MVP / MVM / MCITP / MCTS / MCAD / CCNA / QAI
Microsoft SQL Server MVP / Mind Cracker MVP

Website : http://www.kaashivinfotech.com/
Blog : http://venkattechnicalblog.blogspot.com/
Profile : http://beyondrelational.com/members/jvprabhusanthi/default.aspx

Check my Microsoft Profile for more details about me : https://mvp.support.microsoft.com/default.aspx/profile/venkatesan
-------------------------------------------------------------------------------------------
Hi Venkat,

Did you get a chance to look at this email?

Regards
Alex Madaswamy
On Fri, Jan 28, 2011 at 2:31 PM, > wrote:
Hi Venkat,

I was looking through some forums to find a solution my issue and got your blog information and your email id. Can you please help me to resolve this issue?

We have a table with more than 1M records and we are retrieving records from this table in my application. This was working fine till two days back, but now its throuwing an error. See below the query and the error message we are getting.

select * from Production_Table WHERE [Rep_Code] IN ('117','118','146','147','148','701','702','704','705','706','707','709','710','711','712','713','202') and Rep_Type LIKE '6%' and CONVERT(VARCHAR(8),CONVERT(DATETIME,(Load_Date)),112) between '20110120' and '20110126'

Please note:
All the fields in WHERE condition are of the data type VARCHAR
Values in the field Load_Date is in the format yymmdd

Error message:
Server: Msg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

I tried this as well:

Removed the condition for the Load_Date from the WHERE condition and ran the query with just Rep_Code and Rep_Type, query returns the value without any issue.
Removed the condition for the Load_Date from the WHERE condition and included in the SELECT part and ran the query with just Rep_Code and Rep_Type, query runs well without any issue. Below is the modified query.
SELECT CONVERT(VARCHAR(8),CONVERT(DATETIME,(Load_Date)),112) FROM from Production_Table WHERE [Rep_Code] IN ('117','118','146','147','148','701','702','704','705','706','707','709','710','711','712','713','202') and Rep_Type LIKE '6%'
Can you please help me to find a solution for this issue?

Thanks in advance,
Alex Madaswamy

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