28.3.10

Rename the table in SQL Server

sp_rename is used to rename the objects.

The syntax is,

sp_rename "Old Object Name","New Object Name"

Code Sample:


drop table Venkat_Table
create table Venkat_Table (id int)
-- Rename the existing table.
exec sp_rename 'Venkat_Table','Venkat_Table_New'
-- To check whether the table is available or not.
-- OR to check the properties of the table.
sp_help 'Venkat_Table_New'

Cheers,

Venkatesan Prabu .J

27.3.10

Delete duplicate records in SQL Server

==========================================================================================
/* TABLE WITH MULTIPLE COLUMNS*/
==========================================================================================
Considering this table is a stand alone table with multiple columns and there is no identity.
Select the distict values into temp table, drop the existing table and rename the temp table into the original table.
==========================================================================================
drop table venkat
create table venkat(id int ,nam varchar(100))
insert into venkat values (1,'Arun')
insert into venkat values (1,'Arun')
insert into venkat values (1,'Arun')
insert into venkat values (2,'Arun1')
insert into venkat values (2,'Arun1')
select * from venkat
-- GET DISTINCT RECORDS INTO TEMP TABLE.
SELECT DISTINCT * INTO temp_Venkattable FROM venkat
-- DROP EXISTING TABLE.
DROP TABLE venkat
-- RENAME THE NEW TABLE TO EXISTING TABLE.
EXEC sp_rename 'temp_Venkattable','venkat'
select * from venkat
-- IF THE TABLE IS NOT A STAND ALONE TABLE, YOU CAN'T DO THE ABOVE PROCESS. BEFORE ACHIEVING IT,
--YOU NEED TO CONSIDER ALL THE DEPENDENCIES ON THE TABLE
==========================================================================================
/* TABLE WITH IDENTITY COLUMN*/
==========================================================================================

Considering this table having an identity column. In that case, our work is too simple.
==========================================================================================

drop table venkat
create table venkat(id int IDENTITY ,nam varchar(100))
insert into venkat values ('Arun')
insert into venkat values ('Arun')
insert into venkat values ('Arun')
insert into venkat values ('Arun1')
insert into venkat values ('Arun1')
select * from venkat
DELETE FROM VENKAT WHERE ID NOT IN
(SELECT MIN(ID) FROM VENKAT GROUP BY NAM)
select * from venkat
==========================================================================================
/* TABLE WITH SINGLE COLUMNS*/
==========================================================================================
drop table venkat
create table venkat(nam varchar(100))
insert into venkat values ('Arun')
insert into venkat values ('Arun')
insert into venkat values ('Arun')
insert into venkat values ('Arun1')
insert into venkat values ('Arun1')
select * from venkat
-- CTE IS THE VERY BEST OPTION TO DELETE THE DUPLICATE RECORDS IN SQL SERVER 2005
with cte as (
select row_number() over ( partition by nam order by nam ) as id ,nam from venkat
)
delete from cte where id !=1
==========================================================================================

14.3.10

SSIS Error

I got a chance to connect Oracle database from SQL Server. Below are the steps done,


1. Created an Oracle DB connection.

2. Created an Execute SQL Task.

3. Select the DB connection and typed the query needed.

"DELETE FROM TABLE WHERE ID=10;"



OOPS!!! I got the below error message,



Error: ORA-00911: invalid character



On analysing this issue, You should not have the ";" character at the end. Just remove it and try it. That's nice to hear the word... working fine.

Cheers,
Venkatesan Prabu .J

9.3.10

SQL Server 2000 DTS Designer components

I got a chance to work with SQL Server 2000 package migration to SQL Server 2005,
While trying to open SQL 2000 DTS package in SQL Server 2005, I got the below error message,
"SQL Server 2000 DTS Designer components are required to edit DTS packages. Install the special Web download, "SQL Server 2000 DTS Designer Components" to use this feature."

I think, am missing something in my installation. Googled a little bit, found some interesting stuffs.

Microsoft is advising us to install SQLServer2005_DTS.msi located in the below path,
http://www.microsoft.com/downloads/details.aspx?familyid=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en&displaylang=en

or else, you can try some other alternative by hacking your sqlwb manifest file,

http://support.microsoft.com/default.aspx/kb/917406

Happy Learning!!!
Cheers,
Venkatesan Prabu .J

Interview question on real time data restoring

Sent: Thursday, 11 February 2010 11:34 AMTo: Venkatesan Prabu JSubject: SQL server 2005 help
Hi Venkatesan,

I am member of dot net spider and I require a help from you.
Please provide your help in this regard.

Recently, I went for an interview where they asked me this question

Question: Assume that I have a flat file with more than a million records. I have to insert this in the production database without performance hit for the users? The application is a 24 X 7 application.

My answer: Since we want to do the insert in production database, we would check if there are any maintenance window available. If one is available we would do it during the window by using bulk copy or import data or some schedule job which would read the file and insert into the table.

But the interviewer asked me how do you do it when there are no maintenance window. my answere now was, it is risky to do in production database when users are using the application. But still if you want to continue, try inserting small chunks (say 1000 records). Lock the table, insert 1000 records and release the lock, so that the user would not feel the performance hit.

But still the interviewer was not convinced and expected something more.

Since i am new to sql server 2005, can u pls help me by giving a solution to this scenario.

Thanks
Saravanan


---------------------------------------------------------------------------------------------
Sent: Mon, 1 March, 2010 3:55:10 PMSubject: RE: SQL server 2005 help
Dear Saravanan,

Your answer is not correct.

1. You should not lock the table which is available for 24/7.
2. You should have another table(With same schema and everything) with all the data from the existing table. Insert all the records into the table.
3. Rename the existing table with temp in the prefix.
4. Rename the new table with old table using sp_rename option.

Probably, I will post a detailed explanation in my blog. Hope, you are happy with this explanation.

Thanks and Regards,
Venkatesan Prabu .J
Microsoft SQL Server MVP/HCL SQL Knowledge Champion/DNS MVM Award Winner
MCITP/MCTS/MCAD/CCNA/QAI
B.B Certified Asp.net/C#/RDBMS/Networking professional
E.R certified Networking candidate

http://venkattechnicalblog.blogspot.com/
----------------------------------------------------------------------------------------------

Sent: Thursday, 4 March 2010 12:15 PMTo: Venkatesan Prabu JSubject: Re: SQL server 2005 help
Dear Venkatesan,

Thanks a lot for your reply.
I really appreciate in taking your valuable time to respond to my query.

However, i have one doubt in your solution. If we do the manipulation in the temporary table, any transaction that happened to the original table would be lost right.

Thanks
Saravanan

----------------------------------------------------------------------------------------------
Sent: Thu, 4 March, 2010 2:47:17 PMSubject: RE: SQL server 2005 help

Dear Saravanan,

That's a very nice question.

For this kind of huge work, always there will be a little hickup which we can't control.

considering the table name is VenkatTable.

1. Put your table as VenkatTable_New
2. Rename the existing table as VenkatTable_Old
3. Rename the table VenkatTable_New as VenkatTable.
4. Migrate the new data from VenkatTable_Old to VenkatTable.

Problem arises, If you have constraints. In that case,

1. Disable the constraints before doing this and enable the constraints after your process.

Enjoy....

Thanks and Regards,
Venkatesan Prabu .J
Microsoft SQL Server MVP/HCL SQL Knowledge Champion/DNS MVM Award Winner
MCITP/MCTS/MCAD/CCNA/QAI
B.B Certified Asp.net/C#/RDBMS/Networking professional
E.R certified Networking candidate


http://venkattechnicalblog.blogspot.com/
-----------------------------------------------------------------------------------------------

Dear Venkat,

Thanks a lot for your response. That gave me a good idea.

Thanks
Saravanan

4.3.10

Add or subract month or year or day in SQL Server

Get Previous month:

Dateadd is a handy command to add or subtract the days/month/year in a specified date column.
The syntax is Dateadd(type,datecolumn)
type may be dd or mm or yy
Below is the query to get the current date:
select getdate()
I need the previous month (Same day). Then, the query should be modified as,
select dateadd(mm,-1,getdate()) -- dateadd(yy,1,getdate())
If I need to retrieve next year with same day and sae month. Then,
select dateadd(yy,1,getdate())



Cheers,
Venkatesan Prabu .J

Execution time of the stored procedure

How to find the execution time of a stored procedure?

There are two options to find the execution time of the stored procedure,

First Option:
Get the current time before execution. Execute the stored procedure. Get the current time after execution. Manipulate the difference in times which will provide you the exact execution time.

declare @startproc datetime
declare @endproc datetime
declare @time integer
select @startproc = getdate()
exec VenkatProc(Your procedure name)
select @endproc = getdate()
select @time = DATEDIFF(second, @startproc, @endproc)
print str(@time)

Second Option:
Get Use profiler to get the exact time taken + split up period like, time taken by each query + time taken to read or write.

Cheers,
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