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'

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.

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
