27.6.10

Setting the application name - Ease to monitor the application performance

Sometimes, we used to monitor the performance of our application. In that case, I have seen the application name is generic. For instance, If we use 2 dotnet application to access the database both were showing the application name as ".Net SQLClient Data provider". Oops, Is there any way to segregate this?

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

I got a chance to create a report in SQL Server 2008 and deploy the same in IIS. Below is error recieved.

"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

I have written an aricle to fetch the properties of SQL Server agent, Check my article in the below link,

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

DBCC Showcontig will give a detailed insight on the data pages(OS level) for the tables.


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

DBCC SQLPERF(umsstats) - This command will provide all the OS related information for your threads in the SQL Server instance. It provides the below values,

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

Re-indexing the entire database:

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
To find the free space available in the log files:

Below is the command used to identify the amount the space available or percentage used.

DBCC SQLPERF (LOGSPACE)


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


Scenario:

Usually, we will face log space issue in our SQL Server. Most of the time, we dont know the reason for our logfile space. I would suggest to get a third party tool to check it. By reading through some of the forums. I found there is some undocumented DBCC command which is used to dig the log file and get some information to us.

This command won't give a very great information at least we can get some high level information. Let's see the command,
DBCC Log(Databasename, Option number)

Default option number is 0

For instance,

dbcc log ('master',0) - 0 indicates a very minimal information.

The above command will provide the below details,


The above output won't give more information let's try with some other option values.

Now, am trying the option 1

dbcc log ('master',1) - This will provide some moreinformation like log description, Log record length, log reserver etc.,

Now, am trying the option 2

dbcc log ('master',2) - This will provide some more information like PageId, slot ID, Lock details etc..,


Now, am trying the option 3

dbcc log('master',3) - This will provide lot of information to us like object name, database name, transaction details like transaction start time /end time/transaction id etc..,



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

Publishing your database :


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

On clicking the next, you will get the database to be pulished. select the database and click "next" button.
On clicking the check box "Publish all objects in the selected database" you wont get the below window. By default, it will select all the objects and bypass the below window.


In the previous window, I have selected tables. So the next window will list down all the tables available in the database.


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.
To select the database click new -> provide the server + database + authentication information and click "Ok" button.

On clicking the "Ok" button. the next window will start creating the scripts in the source and try to connect and execute the same in the destination database.
1. Drop existing objects in script -> On selecting "True" drop statements will be included in the script.
2. Publish using transaction -> Entire script will be loaded with transactions logic. Entire script will be executed and if there is any issue entire script will get rollbacked.
3. Schema qualify - True will provide the entire objects with fully schema qualified one else only object name will be used. Advisable to have this option as "True"
4. Script for target database - You will have the option to select the target database type. Is it SQL Server 2005 or SQL Server 2008.
5. Type of objects to publish - Schema only or Data only or Schema and Data options.


On clicking next button -> Summary of all the actions done by us in the previous windows will be displayed.

On clicking finish button. Fetching the scripts from the source -> connect to the remote server -> Execute in the remote server.


Cheers,
Venkatesan Prabu .J

13.6.10

Error in inserting records in SQL Server

I got a message from one of the forum member in this site and I would like to provide some suggestions on the same.

-------------------------------------------------------------------------------------------------
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
*******************************************
" runat="server">InsertCommand="INSERT INTO myTb(name, username, password, emailid) VALUES (@name, @username, @password, @emailid)" SelectCommand="SELECT myTb.* FROM myTb">

============================================================

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

To list the 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

How to concatenate two columns in the result set 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

Using set statement, you can't set more than one value where as in select we can
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

In previous version of SQL Server, we dont have option of initialising the varaibles during declaration.

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

While trying to modify the table, I got a peculiar message box in SQL Server 2008. It's allowing me to change the property of a table or any object. Searching in MSDN, I have end up with the exact solution to resolve this issue. Below is the solution,

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,
Venkatesan Prabu .J







Find index associated with the table in SQL Server

Below are some of the ways to identify the indexes available on a particular object.

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

Unfortunately, I got some error in my SQL throwing the below error string,

"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

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



Cheers,
Venkatesan Prabu .J