25.5.12

Option to access the Column Names in Data table


Here is the option to access the column (header) name of a datatable.

DataSet ds = new DataSet();
ds.Tables[0].Columns[0].ColumnName

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

Open multiple windows in browser startup. (Multiple homepages option)

If you want to open two sites simultaneously, there is an option available in IE. Just go to Options page of your IE browser and provide multiple URL’s. Click “Apply” and “Ok”. Close the browser and start the browser once again. Eureka, hope you are able to see two tabs opening simultaneously.





Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

20.5.12

Upgrading the version from Evaluation to Standard/Enterprise/Developer version

For the people who are using evaluation version of Microsoft SQL Server, you will face the below problem after a certain period. While trying to access SSMS. You will get this error.
Evaluation period has expired. For information on how to upgrade your evaluation software please go to http://www.microsoft.com/sql/howtobuy (http://www.microsoft.com/sql/howtobuy)

There are two ways to fix the above error message:
1. Install Service Pack 1 before upgrading SQL Server 2008 evaluation edition to any licensed edition.
2. Modify Registry. Go to Start->Run->Regedit. In the Registry Editor, select the following keyHKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\100\ConfigurationState and change the value of the Common Files REG_DWORD to 3 as shown in the figure below.
http://msdn.microsoft.com/en-us/library/ms143393.aspx




After completing the registry changes, run the edition upgrade and you are done. For a list of supported version and Edition upgrades, check out the following:




You need to provide appropriate keys and install the software or upgrade the software successfully.

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

15.5.12

Query to Create comma separated Output.





Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

How can we force SQL Server to use a specific index when executing a query?





Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

Query in one of the forum:



using Below sample query(2 times same query with one condition as extra) to get the 2 type of result set.

IF @Status = 'A'
Select * From TableName where ID = @ID and Value > 200
Else
Select * From TableName where ID = @ID

How can i use Case statement to avoid to create the same select statement 2 times.


Here is my answer to achieve the same.





Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 


REBUILDING VS REORGANIZE THE INDEX


When an index is rebuilt, it is dropped and a new one is created.
In the process fragmentation is removed and disk space is reclaimed.

ALTER INDEX PK_CustId ON Sales.Customer REBUILD

REORGANIZE THE INDEX
Minor Level modification, so that rearranging of the tree node is done.
 Small Fragmentation is removed, the index remains.

ALTER INDEX PK_CustId ON Sales.Customer REORGANIZE

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 

Variable in Top Clause (Dynamic value for the top clause):


Suppose, If we want to pass the arguments for getting top number of records we can achieve it by declaring the variable and using the variable as below.




Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 


Get the Top Data with Ties from SQL Server (If there are same data….Ties in data will happen. If we need all the data.)


In this scenario you need to use With Ties option





In the second query, I’ve given Top 3 data. But the third and fourth data is having a tie up which inturn enables the query engine to fetch both the data which are in Ties.

·         WITH TIES OPTION MAY CAUSE MORE THAN THE SPECIFIED NUMBER OF RECORDS TO BE DISPLAYED

·         BECAUSE IT DISPLAYS ALL OF THE RECORDS MATCHING THE LAST RECORD'S ORDER BY CLAUSE

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 










Get the Top Data from SQL Server



Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 


How to use dynamic sql for a nvarchar of more than 4000 characters?


Usually, it's a typical problem we will face while executing the Dynamic SQL the length of the string is really huge when compared to the max length of the string. To overcome this major issue. Here is a small alternative. We can have part of the execution string in one variable and remaining part in the other string.
  A small example

find columns having index?
 sp_helpindex  tblUserDetails


sp_help tblUserDetails





EXEC sp_msforeachtable @command1= "PRINT '?'  
EXEC sp_helpindex @objname = '?'"


Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 

SET or SELECT -- is there any performance difference?


It doesn't have major performance difference between the Set and Select statement. The only thing is the usability nature of the commands.

            SET @variable = (SELECT datacolumn FROM tablename)
The above statement should return a single value which will be assigned to the variable. Here, if the results of the subquery expression is empty then @variable has a value of NULL but if the results of the subquery are more than one row then you get a error.
And thus it makes sense while,

SELECT @variable = columnvalue FROM dbo.tablename

returns a value from a number of rows and we are not sure what’s the criteria in selecting that row.

 One major difference in assigning using SET and SELECT is:

SET @variable1 = 'somevalue', @variable2 = 'someothervalue'

This is NOT possible but the same is possible with SELECT as in:

SELECT @variable1 = 'somevalue', @variable2 = 'someothervalue' 

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 

Difference between Stored Procedure (SP) and User Defined Function


Ø   User Defined Function can be executed using the “SELECT” clause whereas Stored Procedure cannot be Executed..
Ø    User Defined Function does not return any output parameters while Stored Procedure will return output parameters.
Ø   User Defined Function cannot make permanent changes to server environments while SP’s can change some of the server environment.
Ø   If there is an error in UDF its stops executing. But in SP’s it just ignores the error and moves to the next statement.

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx 

14.5.12

Chief Guest for Jaya Engineering College, Faculty Development program



Chief Guest for Jaya Engineering College, Faculty Development program on Microsoft Technologies

Program Coverage : 

      Session 1:  Talk on Latest  Microsoft Technologies (WCF, WPF, Cloud Computing, Dotnet Framework, Denali, Web Matrix, Windows Server 2008)

      Session 2:  Talk on basic C# and Dotnet Framework Concepts.



My talk about Cloud Computing (SQL Azure and WinAzure):


Talk about Denali and it's new Features:





It was a fantastic session and I really enjoyed the arrangements and facilities provided for this program. Had a great lunch :-) and came back to my office.

Thanks to Anna University and Jaya Engineering College for arranging this session.

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
For free Ebook : http://kaashivinfotech.com/Ebooks.aspx

10.5.12

Join tables from different databases

This can be achieved by joining the tables or indicating the tables using Fully Qualified names.




SELECT t1.id, t1.name


FROM AdventureWorks.dbo.Venkat_Table1 t1


INNER JOIN


AdventureWorksLT2008R2.dbo.Venkat_Table2 t2


ON t1.id = t2.id



Programmatically find out when SQL Server service is started

1. First Option is to check when the tempdb database is created. This is the exact time at which the services were restarted.





SELECT crdate AS 'SQL Server service started Time'


FROM master.dbo.sysdatabases


WHERE name = 'tempdb'




2. Second Option is the information about the database startup will be available while executing the command,


exec xp_readerrorlog

 
 
                       

Find the execution time of a stored procedure

The best way is to use SQL profiler. Just choose the required events.Else if you dont have the permission to access SQL Profiler or want to determine that programatically, then try:


DECLARE @StartDate datetime, @EndDate datetime
SET @StartDate = getdate()

/*

--Exec your stored procedure code here--

*/

SET @EndDate = getdate()
SELECT datediff(ms,@StartDate, @EndDate) AS 'Milliseconds'

Avoiding prefix 'sp_' in the name of user stored procedure

By nature, if the stored procedure is created with the prefix sp_. SQL Server will start search for the stored procedure in the master database. After wards, it will search for the local database which in turn a major problem. To avoid this,



We need to access the stored procedure using Fully Qualified Name,

DatabaseName.SchemaName.ProcedureName

Deleting backup and restore history

Usually, backup and restore history will be available in the MSDB database(Microsoft Database). It’s advisable to cleanup the database after archiving the databases.




Scenario: Considering, am having daily backups and after two years the database will be archived. In that case, the backup and restore information which is happened before two years need not be maintained and we can go for cleanup. In that case, we are using the below command to cleanup the database. You need to specify the exact dates. So that, data before that dates will be cleaned up.



USE msdb


EXEC sp_delete_backuphistory '1/31/2011'

4.5.12

Get Recent records from the table

Here is a small code snippet for getting the recent records from the table.

drop table VENKAT_TABLE
go
create table Venkat_Table(code varchar(100),rate decimal(10,8),date1 date)
go
insert into VENKAT_TABLE values ('sam', 1.240000, '01/08/2004')
insert into VENKAT_TABLE values ('sam', 1.840000, '02/08/2004')
insert into VENKAT_TABLE values ('pal', 1.240000, '01/08/2005')
insert into VENKAT_TABLE values ('pal', 0.840000, '10/08/2003')

select code,rate,date1 from
(
select ROW_NUMBER() over (partition by code order by date1) as rank1,*
  from VENKAT_TABLE ) t
  where rank1=1
 
Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
 

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