Counter of Festivals

Ashok Blog for SQL Learners and Beginners and Experts

Wednesday 30 October 2013

To know Server name and instance name in SQL Server



set nocount on

Declare @key Varchar(100), @PortNumber varchar(20)

if charindex('\',CONVERT(char(20), SERVERPROPERTY('servername')),0) <>0

begin

set @key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server\'+@@servicename+'\MSSQLServer\Supersocketnetlib\TCP'

end

else

begin

set @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib\TCP'

end

EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key,@value_name='Tcpport',@value=@PortNumber OUTPUT

SELECT CONVERT(char(20), SERVERPROPERTY('servername')) ServerName,

CONVERT(char(20), SERVERPROPERTY('InstanceName')) instancename,

CONVERT(char(20), SERVERPROPERTY('MachineName'))

as HOSTNAME, convert(varchar(10),@PortNumber) PortNumber


Tuesday 29 October 2013

Exists and IN operator to find Not present numbers in when compare two tables

Exists and IN operator to find Not present numbers in when compare two tables

There are two tables in db like student and course as see below:


Here u can see courseadmin column have no 8 is missing in Course Table when compared to Student table like studentid

Note:
(here Courseadmin is nothing but studentid who have studying course in course table)


So Hence to find not present no's when compare two tables

first put large table as first like up and low as second like below structures

student table(all value present table)

operator

course table(value missing table)

So, see below to find two methods 









Row_number() over(order by) Function Usage methods in Scripts

Row_number() over(order by) Function Usage methods in Scripts


When u use row_number() over usage u have to follow below methods other wise u can get error


sample table

select * from  testdb.[dbo].[Employee_Test]



When u use select without alias table then u can get Error as see below:


But u can select row_number() function with following two methods

Method 1:

Method 2:










Monday 28 October 2013

How to increase Table column length size with Table Data?

How to increase Table column length size with Table Data?


When table have a data then u cant able to modify column size's like
while you do Right click table and click modify then increase/decrease size then u can get error like see below:




But to avoid this error  u can use T-SQL code like

ALTER TABLE TABLENAME ALTER COLUMN DATATYPE() 



Tuesday 22 October 2013

Comma Separated Values in SQL Server

Comma Separated Values in SQL Server


select substring(
(select ','+j.jobsdescription from jobdetails J
order by j.jobid
FOR XML PATH('')),2,500) AS CDM


Date import from excel sheet to SQL Server

                                    Insert Excel sheet values to SQL Server 2005


First of all Turn on the adhoc Distributed Quries in your SQL Server using below statement

sp_configure 'Ad Hoc Distributed Queries',1

reconfigure

SELECT * 
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
                'Excel 8.0;Database=D:\SQL\JobDetails.xls',
                'SELECT * FROM [Sheet1$]')


Now u can view the excel data in your SQL SERVER DB.

If u want to insert values as table use as same below

SELECT * into jobdetails
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
                'Excel 8.0;Database=D:\SQL\JobDetails.xls',
                'SELECT * FROM [Sheet1$]')

select * from jobdetails


Friday 18 October 2013

How do we change db schema to dbo?

How do we change any database schema owner to dbo?



select * from [Production].[Location]


ALTER SCHEMA DBO TRANSFER Production.Location


select * from Location----------return rows

select * from dbo.Location------return rows

select * from [Production].[Location]-----no rows return  due to schema changed from production  to dbo


Wednesday 16 October 2013

To Understand the SQL Server NOLOCK hint

To Understand the SQL Server NOLOCK hint

Example
Let's walk through some simple examples to see how this works. (These queries are run against the AdventureWorks database.)
Here is a query that returns all of the data from the Person.Contact table. If I run this query I can see there is only one record that has a Suffix value for ContactID = 12.
SELECT * FROM Person.Contact WHERE ContactID < 20
use of the nolock(aka readuncommited) hint
Let's say another user runs the below query in a transaction. The query completes and updates the records, but it is not yet committed to the database so the records are locked.
-- run in query window 1
BEGIN TRAN
UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID < 20
-- ROLLBACK or COMMIT
If I run the same query from above again you will notice that it never completes, because the UPDATE has not yet been committed.
-- run in query window 2
SELECT * FROM Person.Contact WHERE ContactID < 20
If I run sp_who2 I can see that the SELECT statement is being blocked. I will need to either cancel this query or COMMIT or ROLLBACK the query in window one for this to complete. For this example I am going to cancel the SELECT query.
commit or rollback query
To get around the locked records, I can use the NOLOCK hint as shown below and the query will complete even though the query in window 1 is still running and has not been committed or rolled back.
-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
If you notice below the Suffix column now has "B" for all records. This is because the UPDATE in window 1 updated these records. Even though that transaction has not been committed, since we are using the NOLOCK hint SQL Server ignores the locks and returns the data. If the UPDATE is rolled back the data will revert back to what it looked like before, so this is considered a Dirty Read because this data may or may not exist depending on the final outcome in query window 1.
using the nolock hint sql server ignores the locks
If I rollback the UPDATE using the ROLLBACK command and rerun the SELECT query we can see the Suffix is back to what it looked like before.
-- run in query window 1
ROLLBACK

-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
-- or
SELECT * FROM Person.Contact WHERE ContactID < 20
using the rollback command
So the issue with using the NOLOCK hint is that there is the possibility of reading data that has been changed, but not yet committed to the database. If you are running reports and do not care if the data might be off then this is not an issue, but if you are creating transactions where the data needs to be in a consistent state you can see how the NOLOCK hint could return false data.

Locks

So what kind of locking is used when the NOLOCK hint is used.
If we run our SELECT without NOLOCK we can see the locks that are taken if we use sp_lock. (To get the lock information I ran sp_lock in another query window while this was running.)
SELECT * FROM Person.Contact WHERE ContactID < 20
we can see the locks that are taken if we use sp_lock
If we do the same for our SELECT with the NOLOCK we can see these locks.
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
sql server still creates a lock to make sure the data is consistent
The differences are that there is a "S" shared access lock that is put on the page (PAG) that we are reading for the first 19 rows of data in the table when we don't use NOLOCK. Also, we are getting a Sch-S lock versus an IS lock for the table (TAB).
So another thing to point out is that even when you just SELECT data SQL Server still creates a lock to make sure the data is consistent.
These are the lock types and the lock modes that are used for the above two queries.

Lock Types

  • MD - metadata lock
  • DB - database lock
  • TAB - table lock
  • PAG - page lock

Mode

  • S - Shared access
  • Sch-S - Schema stability makes sure the schema is not changed while object is in use
  • IS - Intent shared indicates intention to use S locks

READUNCOMMITED

The NOLOCK hint is the same as the READUNCOMMITED hint and can be used as follows with the same results.
SELECT * FROM Person.Contact WITH (READUNCOMMITTED)

SELECT statements only

The NOLOCK and READUNCOMMITED hints are only allowed with SELECT statements. If we try to use this for an UPDATE, DELETE or INSERT we will get an error.
UPDATE Person.Contact with (NOLOCK) SET Suffix = 'B' WHERE ContactID < 20

Msg 1065, Level 15, State 1, Line 15
The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE, DELETE or MERGE statements.

Schema Change Blocking

Since a NOLOCK hint needs to get a Sch-S (schema stability) lock, a SELECT using NOLOCK could still be blocked if a table is being altered and not committed. Here is an example.
-- run in query window 1
BEGIN TRAN
ALTER TABLE Person.Contact ADD column_b VARCHAR(20) NULL ;
If we try to run our SELECT statement it will be blocked until the above is committed or rolled back.
-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20

Issues

We mentioned above how you can get dirty reads using the NOLOCK hint. These are also other terms you may encounter for this hint.
  • Dirty Reads - this occurs when updates are done, so the data you select could be different.
  • Nonrepeatable Reads - this occurs when you need to read the data more than once and the data changes during that process
  • Phantom Reads - occurs where data is inserted or deleted and the transaction is rolled back. So for the insert you will get more records and for the delete you will get less records.
To learn more about these issues read this article: http://msdn.microsoft.com/en-us/library/ms190805.aspx

Isolation Level

You can also set the Isolation Level for all queries instead of using the NOLOCK or READUNCOMMITTED hint. The isolation level will apply the READUNCOMMITTED to all SELECT statements that are performed from when this is turned on until it is turned off.
In the example below, the two SELECT statements will use the READUNCOMMITED or NOLOCK hint and the UPDATE will still function as normal. This way you can set a whole batch of statements instead of modifying each query.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; -- turn it on

SELECT * FROM Person.Contact WHERE ContactID < 20

UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID = 1

SELECT * FROM Person.Contact WHERE ContactID < 20

SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off

Tuesday 15 October 2013

Important T-SQL commands to know LDF and MDF file name and shrinking File

Important T-SQL commands to know LDF and MDF file name and shrinking 

file


---To know the size of Database and free space in MB------------

SELECT DB_NAME(database_id) AS DatabaseName,
sum(size/128.0) [Size in MB],sum(size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0)[Free Space in MB]
FROM sys.master_files
where DB_NAME(database_id)=db_name()
group by DB_NAME(database_id)

sp_helpdb 'northwind'

SELECT 12480/1024 as GB


--------------To know the logical file name like MDF and LDF file----------------------

select * from sys.databases
where name='northwind'

SELECT * FROM sys.database_files

sp_helpfile 'northwind'


----------------------------To take the backup of db and log backup---------------------

BACKUP DATABASE northwind
TO DISK = 'F:\northwind_bk.bak'
--
BACKUP LOG northwind
TO DISK = 'F:\northwind_Log.bak'

----------To alter the Database Recovery model/switch the recovery model---
ALTER DATABASE northwind
SET RECOVERY SIMPLE;
GO
 --Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (Northwind_log, 1);
GO
 --Reset the database recovery model.
ALTER DATABASE northwind
SET RECOVERY FULL;

-------------------------------Shrinking whole DB -------------------

DBCC SHRINKDATABASE (northwind)

------------To know db status----------------------------


select name,log_reuse_wait_desc,recovery_model_desc,state_desc,* from sys.databases 
where name='northwind'
--where log_reuse_wait_desc<>'NOTHING'
--where log_reuse_wait_desc='REPLICATION'
----where log_reuse_wait_desc='LOG_BACKUP'
--where log_reuse_wait_desc='CHECKPOINT'