Venkatesan Prabu MCITP,MCAD,MCTS,CCNA. Worked as a ProjectLead(Senior .Net developer,SQL DBA). Now, Managing Director of KAASHIV INFO TECH, Chennai This Blog aims in serving the community in a better way. This blog is read by developers in 159 countries with average of 400 hits per day. Please post your valuable suggestions and hold my hand to serve the community. Lets make a new world with good thoughts and good minds....... This blog serves the SQL server community all over the world.
27.6.10
Setting the application name - Ease to monitor the application performance
Yes, its possible. We can specify the application name in the connection string. You profiler or activity monitor will provide you the application name as the name specified in your connection string.
Generic connection string (Windows authentication):
Data Source=ServerName; Initial Catalog=DatabaseName; Integrated Security=SSPI; Application Name=MyAppName;
Generic connection string (Windows authentication):
Data Source=ServerName; Initial Catalog=DatabaseName;
Persist Security Info=True;User ID=venkat;Password=venkat;Application Name=MyAppName;
Cheers,
Venkatesan Prabu .J
SSRS - Deployment error
"The report definition is not valid. Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition' which cannot be upgraded."
It's a bug in Visual studio and there is a work around provided. Check the below link,
https://connect.microsoft.com/VisualStudio/feedback/details/361103/reporting-services-report-cant-deploy-to-sql-2005?wa=wsignin1.0
Cheers,
Venkatesan Prabu .J
25.6.10
Database diagram error in SQL Server
Usually, we will face an issue with Database diagrams. Below is the error while trying to create new database diagrams.
This issue is due to access. While upgrading your database or attaching or restoring a lower version of database into higher version of server. You will face this problem.
"Database diagram support objects cannot be installed because this database does not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or the ALTER AUTHORIZATION statement to set the database owner to a valid login, then add the database diagram support objects."
One of the best solution is mapping the database owner to a specific system owner or SQL authentication. For me, this text box is blank and I selected a particular user listed on clicking the small button near to the text box.
Cheers,
Venkatesan Prabu .J
To find recently executed queries in SQL Server
To find recently executed queries,
Select dmStats.last_execution_time as 'Last Executed Time',dmText.text as 'Executed Query' from sys.dm_exec_query_stats as dmStats Cross apply sys.dm_exec_sql_text(dmStats.sql_handle) as dmText Order By
dmStats.last_execution_time desc
Cheers,
Venkatesan Prabu .J
Get Databasename from Database ID in SQL Server
DB_Name(DB_ID) will provide you the database name. The hierarchy is like system tables will have the initial values followed by user databases.
select DB_NAME(1) --- returns Master database
select DB_NAME(2)--- returns Tempdb database
select DB_NAME(3)--- returns Model database
select DB_NAME(4)--- returns MSDB database
select DB_NAME(5)--- returns User database1 etc..,
Cheer,s
Venkatesan Prabu .J
Procedure to get the SQL Agent properties
http://www.c-sharpcorner.com/UploadFile/Blogs/3169/
Cheers,
Venkatesan Prabu .J
All about sys.dm_os_wait_stats DMV
sys.dm_os_wait_stats - This sysem related DMV will provide all the OS related information like,
1. Any I/O acitivity happening.
2. Context switching details
3. Pre-emptive switching.
4. Page / Extent related information.
5. Query waits
6. Memory usage
7. SQL Trace/backup/restore activities.
and Lot more. Try it, you will find a great usage of this DMV.
Cheers,
Venkatesan Prabu .J
Get details on the table contigencies
This command will scan the table and provide the below details,
- Pages Scanned......................... - Number of pages scanned (Denotes the number of pages occupied by this table )
- Extents Scanned..............................: Number of Extents scanned (Denotes the number of Extents occupied by this table )
- Extent Switches..............................: Mixed extents
- Avg. Pages per Extent........................
- Scan Density [Best Count:Actual Count].......: How the data is compacted in the page.
- Extent Scan Fragmentation ...................: Fragmentation from Extent point of view
- Avg. Bytes Free per Page.....................
- Avg. Page Density (full) ...................... (High page density denotes the data is intact and your search will be faster. If the value is less, it indicates your data is scattered.
DBCC SHOWCONTIG --- This command will provide the details for the whole database tables.
DBCC SHOWCONTIG ('Venkat_table') -- This command will provide the necessary information for that particular table.
Cheers,
Venkatesan Prabu .J
Performance monitoring command in SQL Server
Node Id
Avg Sched
LoadSched
SwitchesSched Pass
IO Comp Passes
Scheduler ID (The below data will be populated for each scheduler ID)
online - Whether it's online or not
num tasks - Number of tasks
num runnable - Runnable tasks
num workers - Parallel workers involved in the scheduler
active workers - Active parallel workers involved in the scheduler
work queued - Works queued up in this schedule
cntxt switches - How many context switching happening in this schedule
cntxt switches(idle) - Idle threads after context switches.
preemptive switches - Prirority switches happened in this schedule.
Cheers,
Venkatesan Prabu .J
19.6.10
Reindexing the entire database in sql server
Usually, if the database is too slow. DBA's were advised to re-index the tables. For some cases, we need to rebuild the indexes availables in the entire database.
For this scenario, we can rebuild the index by taking each table and re-index all the indexes associated with each table.
Fill factor:
Amount or compactness of data in the leaf level is defined by the term fill factor. Based on the operations on the database DBA's will decide the fill factor. If the insert/update/delete are very high in that case we will have very less fill factor (Around 60 to 70). If there is very less insert/update/delete, in that case we will have very high fill factor (Around 90). On an average, we will give 80 -90 %.
Below is the script to achieve this,
----------------------------------------------------------------------------
DECLARE @DatabaseTable VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT name AS DatabaseTable
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @DatabaseTable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'DBCC DBREINDEX('+ @DatabaseTable + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @DatabaseTable
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
-------------------------------------------------------------
How abt re-organsing the indexes (Rebuild index vs reorganise index):
1. Re-built can't be done on the production run time (Due to its high impact on rearranging the data and recreate of index) where as re-organise index can be done.
2. Indexes were recreated in case of re-building the index.
3. Re-built index is very effective when compared to the other.
Cheers,
Venkatesan Prabu .J
18.6.10
Inserting DBCC output into a table
Is it possible to insert the data from the DBCC output?
Yes, it's possible. Below are the conditions to achieve it.
1. Considering am taking the DBCC command DBCC log('master',0)
2. I need to push it to a table. So that, I can play around with the data available.
3. Make the command into a dynamic sql using exec command.
4. Create a table with similar structure as the output of the command.
5. Push the data through insert statement. Below is the query sample to achieve it.
create table dbcc_insert_Table(CurrentLSN varchar(100),Operation varchar(100),
contaxt varchar(100), transactionId varchar(100),logblock int)
insert dbcc_insert_Table
exec('dbcc log (''master'',0)')
All the records from the DBCC output will be pushed into the newly created table.
Cheers,
Venkatesan Prabu .J
View Log file information in SQL Server
Now, am trying the option 4
dbcc log ('master',4) - This provides very less information when compared to 1,2,3 option. It's just an enhanced version of option type 0.
Cheers,
Venkatesan Prabu .J
Publishing database wizard - SQL Server 2008
I have created a database with objects. Now, I need to push this database to the external world. How can I achieve it?
SQL Server is providing a very nice option of publishing the database objects using scripting the entire database + publishing to the external database through internet.
Let's see how can we achieve it,
After creating your objects, right click on the database and click tasks ->Publish using webservice option.
You will get the Publish database wizard
Now, we need to select the target database. Database, where we need to push the schema and data. If we have already registered the database, we can select it or else click "Manage" button.
You will get the hosting providers window -> remove the default loaded one and click new button. You will get a window to register the destination server.
You should give the webserive address provided by the provider and the credentials to access this secure webservice.
On clicking next button -> Summary of all the actions done by us in the previous windows will be displayed.
Cheers,
Venkatesan Prabu .J
13.6.10
Error in inserting records in SQL Server
-------------------------------------------------------------------------------------------------
Hello Sir.....I have some problem on SQL Server database and want to ask u as
I am facing the error:
{"Cannot insert the value NULL into column 'name', table 'C:\\DOCUMENTS AND SETTINGS\\ADMINISTRATOR\\DESKTOP\\ARTICLE 17\\SIMPLE LOGIN PROJECT IN ASP.NET\\APP_DATA\\MYDB.MDF.dbo.myTb'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
I have following MSSQL server database
*************************************
id int Unchecked
name varchar(100) Unchecked
username varchar(100) Unchecked
password varchar(100) Unchecked
emailid varchar(100) Unchecked
I am following code in Default.aspx page
*******************************************
============================================================
This above error clearly specifies that, there is an issue with "name" column. We need to check the insert statement at this stage. Because, the name column is not null.
The above issue is due to the @name value passed in the insert statement.
Cheers,
Venkatesan Prabu .J
11.6.10
list column names for a table
In SQL Server, we can retrieve these details by two methods.
1. This can be taken from the sys.objects and sys.columns table (Used in SQL Server 2000 and higher versions).
2. Another option is to use INFORMATION_SCHEMA.COLUMNS (This is introduced in SQL Server 2005 and higher version)
Below is the query to achieve the same,
drop table venkat_table
go
create table venkat_table (id int,val varchar(100),val1 varchar(100))
First Option:
SELECT *FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='venkat_table'
Second Option:
Joining sys.objects and sys.columns table based on the object Id.
SELECT C.name,O.* FROM sys.objects O INNER JOIN sys.columns CON O.object_id=C.object_id WHERE O.name='venkat_table'
Cheers,
Venkatesan Prabu .J
Concatenating two columns in SQL Server
It's too simple. Check the below script,
drop table venkat_table
go
create table venkat_table (id int,val varchar(100),val1 varchar(100))
insert into venkat_table values(1,'Venkat','Prabu')
select ID, val +' '+ val1 as name from venkat_table
Cheers,
Venkatesan Prabu .J
10.6.10
Set Vs Select statement in SQL Server
set more than one value. So we can achieve it in a single line of statement to assign
values to multiple variables. Performance wise there will be a very very small change
and it's good for select.
-- Set statement in SQL Server
declare @val int=0, @val1 int
print @val
set @val=1
-- set @val=1,@val1=2 (You can't set multiple values)
print @val
-- Select statement in SQL Server
declare @val int=0, @val1 int
print @val
select @val=1,@val1=2
print @val
Cheers,
Venkatesan Prabu .J
Inline variable assignments in SQL Server 2008
We have seperate parts like,
1. Declaration part
2. Initialisation
3. Usage.
Whereas, this is bit reduced in SQL Server 2008, Declaration and initialisation can be done as a single one followed by usage one.
Below is a sample query to be executed in SQL Server 2008.
declare @val int=0, @val1 int
print @val -- returns 0
set @val=1
print @val -- returns 1
Cheers,
Venkatesan Prabu .J
SQL Server 2008 message box - Unable to edit the table property
Error Message box content:
saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
SQL Server 2008 holds a new validation to stop the changes happened on a table.
To remove the option,
Goto Tools -> Options->Designers -> Tables and Database designers.
Uncheck the option, prevent saving changes that required table re-creation.
:-) It's an error occured in my table. Resolved the error by myself(Suspense). Am able to edit the table now.
Cheers,
Find index associated with the table in SQL Server
sp_help VENKAT_TABLE (sp_help table_name)
Else, you can use system objects to identify the indexes available on the table. Below is the query to achieve the same,
select * from sys.indexes i inner join sys.objects o
on i.object_id=o.object_id and o.name ='VENKAT_TABLE'
Cheers,
Venkatesan Prabu .J
Temporary table Vs Temporary variable in SQL Server
We have seen lot of difference between temporary variable and temporary table. Here is a nice difference in Transaction perspective.
Temporary table is transaction dependent and it abides to the database transaction whereas temporary variable is not transaction bound.
Sample Query:
---------------------Temporary table -------------------------------
drop table #temp
create table #temp (id int, val varchar(100))
begin tran ins
insert into #temp values (1,'Venkat')
rollback tran ins
select * from #temp
We are not getting any records indicating the temporary table will bound to the transaction strategies.
------------------Temporary variable --------------------------
Declare @tempval table(id int, val varchar(100))
begin tran ins
insert into @tempval values (1,'Venkat')
rollback tran ins
select * from @tempval
Even we have provided rollback transaction. Records are available in the table variable.
Cheers,
Venkatesan Prabu .J
6.6.10
CImageHelper::Init () Failed load of dbghelp.dll - SQL Server error
"CImageHelper::Init () Failed load of dbghelp.dll - Invalid access to memory location"
Reason for this issue:
1. It's a well know issue reported in Microsoft products and it should be a protocol issue. Disabling force encryption for the protocols will resolve the problem.
2. If the problem persists, we need to think in a different perception for this problem. It may be due to memory issue with SQL Server. By default, SQL Server will take the server memory as MAX upto 2147483647 MB (SQL express) and the new process will try to use the new memory instead of utilising the existing memory. In that case, we need to restrict/set the Max server memory capacity. Below is the query to achieve it,
EXEC sys.sp_configure N'max server memory (MB)', N'50'
GO
RECONFIGURE WITH OVERRIDE
GO
After applying above command to the database the memory size is restricted to ~ 50 MB for the same test.
Cheers,
Venkatesan Prabu .J
DateName function in SQL Server
DateName function in SQL Server:
DateName function will be used to fetch the data/month/year/time from the datetime column.
drop table sample_table
create table sample_table (id int, dat datetime)
insert into sample_table values(1,getdate())
select * from sample_table
select id,dat from sample_table where datename(month,dat)='June'
-----------------------------------------
id dat
-----------------------------------------
1 2010-06-07 10:54:52.607
-----------------------------------------
Cheers,
Venkatesan Prabu .J
http://venkattechnicalblog.blogspot.com/
2.6.10
Remove common substring from the strings
I have seen a very different request in one of the popular forum and I would like to write an article on this.
Problem:
Am having a column with string values(as below), I need to remove the substring L1.1 / L1.2 / L2.1 / L3.1 etc..,
'ADM L1.1 Mock Test'
'ADM L2.1 Mock Test'
'.Net L2.1'
The above values needs to be changed to,
'ADM Mock Test'
'ADM Mock Test'
'.Net '
We need to write a generic queries to achieve it,
drop table sample_table
create table sample_table(val varchar(100))
-- Inserting records in the table.
insert into sample_table select 'ADM L1.1 Mock Test' union all select 'ADM L2.1 Mock Test' union allselect 'ADM L2.2 Mock Test' union all select 'ADM L2.3 Mock Test' union all select '.Net L1.1' union all select '.Net L2.1' union all select '.Net L2.2' union all select '.Net L2.3' union all select '.Net L3.1'
select * from sample_table
select SUBSTRING(val,0,CHARINDEX('L',val)) + SUBSTRING(val,CHARINDEX('L',val)+4,LEN(val) )from sample_table
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
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
String Functions in sql server
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.