Tuesday, October 30, 2012

Sql Server All Database Used Space ,Size Info..... Using MSForeachdb

Sql Server All Database Used Space ,Size Info.... Using MSForeachdb

EXEC sp_MSforeachdb 'USE [?]SELECT
A.FILEID,
[FILE_SIZE_MB] =
CONVERT(DECIMAL(12,2),ROUND(A.size/128.000,2)),
[SPACE_USED_MB] =
CONVERT(DECIMAL(12,2),ROUND(FILEPROPERTY(A.name,''SpaceUsed'')/128.000,2)),
[FREE_SPACE_MB] =
CONVERT(DECIMAL(12,2),ROUND((A.SIZE-FILEPROPERTY(A.name,''SpaceUsed''))/128.000,2)) ,
NAME = left(A.NAME,15),
FILENAME =RIGHT(A.FILENAME,CHARINDEX(''\'', REVERSE(A.FILENAME))-1)
FROM
dbo.SYSFILES A'


 

Monday, February 20, 2012

Configuring SQL Server


Configuring Network Protocols from SQL Server configuration manager
SQL Server 2008 is a client-server application designed to efficiently exchange data and instructions over one or more network connections. 

SQL Server 2008 Network Protocols

SQL Server 2008 provides support for four protocols:
· Shared Memory
· TCP/IP
· Named Pipes
· Virtual Interface Adapter (VIA)
By default, the only network protocols enabled for most editions of SQL Server are TCP/IP and Shared Memory. The Developer and Enterprise Evaluation editions are configured with all protocols except Shared Memory disabled during installation, but the remaining protocols can be enabled if required. If a protocol is not enabled, SQL Server will not listen on an endpoint that is configured to utilize that protocol.
The SQL Server Configuration Manager is used to configure server protocols. 

Shared Memory

The Shared Memory protocol can only be used by local connections, because it is a shared memory and process space used for inter-server communication. It has only one configurable property: Enabled. The Enabled property can be set to Yes or No, resulting in a status of Enabled or Disabled.

Named Pipes

Named Pipes uses Inter-Process Communication (IPC) channels for efficient inter-server communication, as well as local area network (LAN) communication. The Named Pipes protocol has some enhancements in SQL Server 2008 including support for encrypted traffic, but because of the excessive overhead of Named Pipes when connecting across networks or firewalls, and the additional port that Named Pipes requires to be opened (445), it is generally a good idea to leave the Named Pipes protocol disabled. However, there are many applications that take advantage of the Named Pipes protocol because they were designed for local network implementations. Named Pipes provides easy access to Remote Procedure Calls (RPC) within a single security domain, and so is advantageous to these applications. If you need to support one of these applications, and the SQL Server is not exposed to external traffic, the risk of enabling the Named Pipes protocol and corresponding endpoint is minimal.
Named Pipes has two configurable properties: Enabled and Pipe Name. The Enabled property works the same as the Shared Memory protocol. The Pipe Name specifies the inter-process pipe that SQL Server will listen on. The default pipe is \\.\pipe\sql\query.

TCP/IP

The TCP/IP protocol is the primary and preferred protocol for most SQL Server installations. It is configured on two separate tabs on the TCP/IP Properties window: the Protocol tab and the IP Addresses tab, as shown 



The Protocol tab has the following four configurable properties:
· Enabled — This works the same as the other protocols.
· Keep Alive — This specifies how many milliseconds SQL Server waits to verify an idle connection is still valid by sending a KEEPALIVE packet. The default is 30,000 milliseconds.
· Listen All — This specifies whether SQL Server will listen on all IP addresses configured on the server.
· No Delay — This option specifies whether the TCP protocol queues small packets to send out larger packets. This queuing is typically undesirable in transaction-based systems, and so it should be left in its default configuration of No.
Surface Area Configuration for services and Connections. 
There are two ways to view the various services and connections on a given server. The first is by instance, and this is usually the easiest method.

However, if you have multiple components on the same server, such as multiple instances of the database engine, it may be easier to group by component, which is what the second tab (View by Component) is for:


Once you've settled on your view, the next step is to actually configure each component. Every component listed will have a Service option where you can configure the startup status for the service as well as control the current state of the service itself. For instance, the following image is of the MSSQLSERVER database engine service, which is set to Automatic, meaning it will start when the computer starts up.

You have the ability to set any of the following startup types:
· Automatic - The service will start when the computer starts up. 
· Manual - The service is capable of being started, but must be started manually by an authorized user (Power Users or Administrators local group membership). 
· Disabled - The service cannot be started unless the startup type is changed.
In addition to the service configurations, the Database Engine and Analysis Services have additional options. For the database engine, there is the Remote Connections configuration.

As the highlighted section shows, you can configure the database engine either to listen only for local connections (originating from the same computer as SQL Server) or to listen for both local and remote connections. In addition, if you choose for SQL Server to listen for remote connections as well, you'll have the choice whether to use TCP/IP, Named Pipes, or both. In general, for network connections, you'll want to use TCP/IP. In my experience, Named Pipes sometimes suffers from timeout issues that you don't get with TCP/IP.

The Dedicated Administrator Connection

In SQL Server 2005, Microsoft introduced a new feature called Dedicated Administrator Connection (DAC). Using this feature a SQL Server Database Administrator can connect to a SQL Server Instance when the database engine is not responding to regular connections. During such a scenario a DBA can connect to the SQL Server Instance to troubleshoot and to kill any of the SQL Server Processes which are causing the issues. 
The DAC allows database administrators to connect to a SQL Server Instance and to execute T-SQL commands to troubleshoot and fix issues rather than rebooting the SQL Server which could lead to database corruption or other problems. By default, the remote Dedicated Administrator Connection feature is disabled in SQL Server 2005 and later versions. It’s a good practice to enable the DAC feature once the SQL Server 2005 or SQL Server 2008 is installed on every instance as this will help you troubleshoot issues when regular connections are not responding. However, only one dedicated administrator connection is allowed at a time on SQL Server 2005 and later versions. 

Enable Dedicated Administrator Connection in SQL Server 2008 Using TSQL


Execute the below T-SQL to enable remote clients to utilize the Dedicated Administrator Connection.
Use master
GO
sp_configure 'show advanced options' , 1
GO
/* 0 = Allow Local Connection, 1 = Allow Remote Connections*/ 
sp_configure 'remote admin connections', 1 
GO
RECONFIGURE
GO
Enable Dedicated Administrator Connection in SQL Server 2008 Using SQL Server 2008 Management Studio
Database Administrators can also enable Dedicated Administrator Connection Feature using SQL Server 2008 Management Studio. This can be done by right clicking the SQL Server Instance and selecting the Facets option from the drop down list as shown in the snippet below. 

This will open up View Facets window as shown in the snippet below. Here you need to select Surface Area Configuration facet as highlighted and then select the option as “True” for RemoteDacEnabled


Finally, click OK to save the configuration changes in the View Facets window.


You can also enable other database engine features like AsHocRemoteQueriesEnabled, ClrIntegrationEnabled, DatabaseMailEnabled, OleAutomationEnabled, ServiceBrokerEndpointActive, SoapEndpointsEnabled, SQLMailEnabled, WebAssistanceEnabled, XPCmdShellEnabled etc when required using the Surface Server Configuration Facet which is available in SQL Server 2008 Management Studio.

Once the Dedicated Administrator Connection is enabled you can connect to SQL Server 2008 using either SQL Server Management Studio or using SQLCMD.

Using DAC with SQL Server Management Studio


You need to specify “ADMIN:” before the SQL Server Instance name when trying to connect to an SQL Server Instance to using DAC feature as shown in the snippet below.

Once you are connected to SQL Server Instance using DAC, then you can execute code such as the code below to check the SQL Server health.
-- Locking Information
SELECT * FROM sys.dm_tran_locks
GO
-- Cache Status
SELECT * FROM sys.dm_os_memory_cache_counters 
GO
-- Active Sessions
SELECT * FROM sys.dm_exec_sessions 
GO
-- Requests Status
SELECT * FROM sys.dm_exec_requests
GO


Wednesday, February 15, 2012

Null value is eliminated by an aggregate or other SET operation


The Problem occurs when an aggregate function(max,sum,avg..) exists on null values. Trying to get rid of the null values may be the solution but in certain cases..you may need the extra data relying on the null values.
So whats the solution?
Append set ANSI_WARNINGS OFF on the beginning of the sql statement.

Wednesday, February 1, 2012

How to Enable the Xp_CmdShell


You can enable the Xp_CmdShell using 2 ways, either by executing T-sql statements or from
"Surface Area Configuration Manager". We'll see both of them.

A. Enable Xp_Cmdshell from Management Studio.
For enabling Xp_CmdShell from Management Studio you need to execute following code.

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

B. Enable the Xp_CmdShell from "Surface Area Configuration Manager."

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Features.
3. Click on xp_cmdshell and tick on checkbox of "Enable the xp_cmdshell".

Friday, January 6, 2012

Msg 468, Level 16, State 9, Line 1 Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.


Sql server Collation Problem and Fix
What is collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying
  • case-sensitivity,
  • accent marks,
  • kana character types and
  • character width.
Case sensitivity
If A and a, B and b, etc. are treated in the same way then it is case-insensitive. A computer treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65, while a is 97. The ASCII value of B is 66 and b is 98.
Accent sensitivity
If a and á, o and ó are treated in the same way, then it is accent-insensitive. A computer treats a and á differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and áis 225. The ASCII value of o is 111 and ó is 243.
Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.
Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.
Production server collation error(Log):
Msg 468, Level 16, State 9, Line 1
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.
Reproduce this error in local QA environment:
How to exploring collation?

Step 1 : What Collation is SQL installed local server identify below query
SELECT SERVERPROPERTY('COLLATION')

Step 2 : Identify databases level Collation
SELECT NAME,COLLATION_NAME FROM SYS.DATABASES
Step 4 : Show the collation for each column in selected database level
SELECT
C.TABLE_CATALOG AS DATABASE_NAME
,C.TABLE_SCHEMA
,C.TABLE_NAME
,C.COLUMN_NAME
,DATA_TYPE
,SERVERPROPERTY('COLLATION') AS SERVER_COLLATION
,CONVERT(SYSNAME,DATABASEPROPERTYEX(D.NAME,'COLLATION')) AS DATABASE_COLLATION
,C.COLLATION_NAME AS COLUMN_COLLATION
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN SYS.DATABASES D
ON DB_ID(C.TABLE_CATALOG) = DB_ID(D.NAME)
WHERE DATA_TYPE IN ('VARCHAR' ,'CHAR','NVARCHAR','NCHAR','TEXT','NTEXT')
In local server level collation ,database level collation and column level collation are same collation (“SQL_Latin1_General_CP1_CI_AS”)
How to Reproduce local environment?
Step 1:Change the database level collation using the below query
ALTER DATABASE FP_Yeti_QA2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE FP_Yeti_QA2 COLLATE Latin1_General_CI_AI
GO
ALTER DATABASE FP_Yeti_QA2 SET MULTI_USER

Latin1_General_CI_AI This is not sql server collation ,This is Windows level collation existing in production server, That why I changed in local server also same collation.

Step 2 :Change table level collation means all column collation using the below script. ( The script will generate all table column collation querys )

DECLARE @Table_Name NVARCHAR(100)
SET @Table_Name = NULL--- THIS IS THE TableName that you want to change its collation columns
--- if null will set to all tables
DECLARE @TempTable AS TABLE
(
ID INT IDENTITY
,TableName NVARCHAR(100)
,ColumnName NVARCHAR(100)
,TypeName NVARCHAR(100)
,Max_length INT
,Collation_Name NVARCHAR(100)
,EnterDtm DATETIME DEFAULT GETDATE()
)
DECLARE @NewCollation NVARCHAR(100)
SET @NewCollation = 'database_default' --- THIS IS THE COLLATION NAME THAT YOU WANT TO CHANGE

INSERT INTO @TempTable(TableName,ColumnName,TypeName,Max_length,Collation_Name)
SELECT
QUOTENAME(SCHEMA_NAME(tables.schema_id)) + '.' + QUOTENAME(tables.name) AS TableName
,all_columns.name AS ColumnName
,type_name(all_columns.user_type_id)
,all_columns.max_length
,all_columns.collation_name
from sys.all_columns INNER JOIN sys.tables ON
tables.object_id = all_columns.object_id
AND collation_name IS NOT NULL
AND all_columns.collation_name != @NewCollation
WHERE tables.object_id = ISNULL(object_id(@Table_Name),all_columns.object_id)

DECLARE @TableID SMALLINT
SET @TableID = (SELECT MIN(ID) FROM @TempTable)

DECLARE @Query NVARCHAR(1000),@TableName NVARCHAR(100),@ColumnName NVARCHAR(100),@TypeName NVARCHAR(100)
,@Size INT

WHILE @TableID IS NOT NULL
BEGIN
SET @TableName = (SELECT TableName FROM @TempTable WHERE ID = @TableID)
SET @ColumnName = (SELECT QUOTENAME(ColumnName) FROM @TempTable WHERE ID = @TableID)
SET @TypeName = (SELECT TypeName FROM @TempTable WHERE ID = @TableID)
SET @Size = (SELECT Max_length FROM @TempTable WHERE ID = @TableID)

SET @Query='ALTER TABLE ' + @TableName + ' ALTER COLUMN ' + @ColumnName + ' ' + @TypeName+ ISNULL ('(' +CAST(@Size AS VARCHAR(200))+')', '') +' COLLATE '+ @NewCollation
PRINT (@Query)
--execute sp_executesql @Query
SET @TableID = (SELECT MIN(ID) FROM @TempTable WHERE ID > @TableID)
END

This is the way to generate script all table in select database level and execute single usermode
Ex:-
ALTER DATABASE FP_Yeti_QA2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
Here column level generating scripts
GO
ALTER DATABASE FP_Yeti_QA2 SET MULTI_USER

How to Error Fix:
Step 1:Change the database level collation using the below query
ALTER DATABASE FP_Yeti_QA2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE FP_Yeti_QA2 COLLATE SQL_Latin1_General_CP1_CI_AS
GO
ALTER DATABASE FP_Yeti_QA2 SET MULTI_USER

SQL_Latin1_General_CP1_CI_AS this is sql server default collation all system databases follow the same collation better we should follow user databases also.

Step 2 :Change table level collation means all column collation inherit the database level collation (database_default) using the below script. ( The script will generate all table column collation querys )

DECLARE @Table_Name NVARCHAR(100)
SET @Table_Name = NULL--- THIS IS THE TableName that you want to change its collation columns
--- if null will set to all tables
DECLARE @TempTable AS TABLE
(
ID INT IDENTITY
,TableName NVARCHAR(100)
,ColumnName NVARCHAR(100)
,TypeName NVARCHAR(100)
,Max_length INT
,Collation_Name NVARCHAR(100)
,EnterDtm DATETIME DEFAULT GETDATE()
)
DECLARE @NewCollation NVARCHAR(100)
SET @NewCollation = 'database_default' --- THIS IS THE COLLATION NAME THAT YOU WANT TO CHANGE

INSERT INTO @TempTable(TableName,ColumnName,TypeName,Max_length,Collation_Name)
SELECT
QUOTENAME(SCHEMA_NAME(tables.schema_id)) + '.' + QUOTENAME(tables.name) AS TableName
,all_columns.name AS ColumnName
,type_name(all_columns.user_type_id)
,all_columns.max_length
,all_columns.collation_name
from sys.all_columns INNER JOIN sys.tables ON
tables.object_id = all_columns.object_id
AND collation_name IS NOT NULL
AND all_columns.collation_name != @NewCollation
WHERE tables.object_id = ISNULL(object_id(@Table_Name),all_columns.object_id)

DECLARE @TableID SMALLINT
SET @TableID = (SELECT MIN(ID) FROM @TempTable)

DECLARE @Query NVARCHAR(1000),@TableName NVARCHAR(100),@ColumnName NVARCHAR(100),@TypeName NVARCHAR(100)
,@Size INT

WHILE @TableID IS NOT NULL
BEGIN
SET @TableName = (SELECT TableName FROM @TempTable WHERE ID = @TableID)
SET @ColumnName = (SELECT QUOTENAME(ColumnName) FROM @TempTable WHERE ID = @TableID)
SET @TypeName = (SELECT TypeName FROM @TempTable WHERE ID = @TableID)
SET @Size = (SELECT Max_length FROM @TempTable WHERE ID = @TableID)

SET @Query='ALTER TABLE ' + @TableName + ' ALTER COLUMN ' + @ColumnName + ' ' + @TypeName+ ISNULL ('(' +CAST(@Size AS VARCHAR(200))+')', '') +' COLLATE '+ @NewCollation
PRINT (@Query)
--execute sp_executesql @Query
SET @TableID = (SELECT MIN(ID) FROM @TempTable WHERE ID > @TableID)
END

Ex:-
ALTER DATABASE FP_Yeti_QA2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
Here column level generating scripts
GO
ALTER DATABASE FP_Yeti_QA2 SET MULTI_USER

Restart the database server.