Simon's SQL

SQL,DBA,tuning,Trouble Shooting,Performance

Archive for April, 2011

Network Monitor

Posted by Simon Cho on 04/27/2011

Information about Network Monitor 3

http://support.microsoft.com/kb/933741

How to capture network traffic with Network Monitor

http://support.microsoft.com/kb/148942

MSDN: Network Monitor

http://technet.microsoft.com/en-us/library/cc938655.aspx

Microsoft Network Monitor 3.4

http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=983b941d-06cb-4658-b7f6-3088333d062f

Kerberos Error Configuring SQL Server Linked Server for Delegation

http://blogs.msdn.com/b/jorgepc/archive/2010/11/30/kerberos-error-configuring-sql-server-linked-server-for-delegation.aspx

Posted in Common | Leave a Comment »

How to troubleshoot the “Cannot generate SSPI context” error message

Posted by Simon Cho on 04/26/2011

http://support.microsoft.com/kb/811889/en-us

This step-by-step article describes how to troubleshoot the most typical sources of the "Cannot generate SSPI context" error message. You may receive this error message under the following conditions:

  • You are connecting to SQL Server.
  • You are using Integrated Security.
  • Kerberos is used to perform the security delegation.

Understanding Kerberos terminology and Service Principal Name

The SQL Server driver on a client computer uses integrated security to use the Windows security token of the user account to successfully connect to a computer that is running SQL Server. The Windows security token is delegated from the client to the computer that is running SQL Server. The SQL Server driver performs this delegation when the user’s security token is delegated from one computer to another by using one of the following configurations:

  • NTLM over Named Pipes (not using Security Support Provider Interface [SSPI])
  • NTLM over TCP/IP sockets with SSPI
  • Kerberos over TCP/IP sockets with SSPI

Security Support Provider Interface (SSPI) is a set of Windows APIs that permits delegation and mutual authentication over any generic data transport layer, such as TCP/IP sockets. Therefore, SSPI permits a computer that is running a Windows operating system to securely delegate a user security token from one computer to another over any transport layer that can transmit raw bytes of data.

The "Cannot generate SSPI context" error is generated when SSPI uses Kerberos to delegate over TCP/IP and Kerberos cannot complete the necessary operations to successfully delegate the user security token to the destination computer that is running SQL Server.

Why Security Support Provider Interface chooses NTLM or Kerberos

Kerberos uses an identifier named "Service Principal Name" (SPN). Consider an SPN as a domain or forest unique identifier of some instance in a network server resource. You can have an SPN for a Web service, for an SQL service, or for an SMTP service. You can also have multiple Web service instances on the same physical computer that has a unique SPN.

An SPN for SQL Server is composed of the following elements:

  • ServiceClass: This identifies the general class of service. This is always MSSQLSvc for SQL Server.
  • Host: This is the fully qualified domain name DNS of the computer that is running SQL Server.
  • Port: This is the port number that the service is listening on.

For example, a typical SPN for a computer that is running SQL Server is:

MSSQLSvc/SQLSERVER1.northamerica.corp.mycompany.com:1433

The format of an SPN for a default instance and the format of an SPN for a named instance are not different. The port number is what ties the SPN to a particular instance.

When the SQL Server driver on a client uses integrated security to connect to SQL Server, the driver code on the client tries to resolve the fully qualified DNS of the computer that is running SQL Server by using the WinSock networking APIs. To perform this operation, the driver code calls thegethostbyname and gethostbyaddr WinSock APIs. Even if an IP address or host name is passed as the name of the computer that is running SQL Server, the SQL Server driver tries to resolve the fully qualified DNS of the computer if the computer is using integrated security.

When the SQL Server driver on the client resolves the fully qualified DNS of the computer that is running SQL Server, the corresponding DNS is used to form the SPN for this computer. Therefore, any issues pertaining to how the IP address or host name is resolved to the fully qualified DNS by WinSock may cause the SQL Server driver to create an invalid SPN for the computer that is running SQL Server.

For example, the invalid SPNs that the client-side SQL Server driver can form as resolved fully qualified DNS are:

When the SQL Server driver forms an SPN that is not valid, authentication still works because the SSPI interface tries to look up the SPN in the Active Directory directory service, and it does not find the SPN. If the SSPI interface does not find the SPN, Kerberos authentication is not performed. At that point, the SSPI layer switches to an NTLM authentication mode and the logon uses NTLM authentication and typically succeeds. If the SQL Server driver forms an SPN that is valid but is not assigned to the appropriate container, it tries to use the SPN but cannot, causing a "Cannot generate SSPI context" error message. If the SQL Server startup account is a local system account, the appropriate container is the computer name. For any other account, the appropriate container is the SQL Server startup account. Because authentication will try to use the first SPN that it finds, make sure that there are no SPNs assigned to inappropriate containers. In other words, each SPN must be assigned to one and only one container.

The key factor that makes Kerberos authentication successful is the valid DNS functionality on the network. You can verify this functionality on the client and the server by using the Ping command-line utility. On the client computer, run the following command to obtain the IP address of the server that is running SQL Server (where the name of the computer that is running SQL Server is SQLServer1):

ping sqlserver1

To see if the Ping command-line utility resolves the fully qualified DNS of SQLServer1, run the following command:

ping -a IPAddress

For example:

C:\>ping SQLSERVER1
Pinging SQLSERVER1 [123.123.123.123] with 32 bytes of data:
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Ping statistics for 123.123.123.123:
 Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
 Minimum = 0ms, Maximum = 0ms, Average = 0ms
C:\>ping -a 123.123.123.123
Pinging SQLSERVER1.northamerica.corp.mycompany.com [123.123.123.123] with 32 bytes of data:
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Reply from 123.123.123.123: bytes=32 time<10ms TTL=128
Ping statistics for 123.123.123.123:
 Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
 Minimum = 0ms, Maximum = 0ms, Average = 0ms
C:\>

When the command ping -aIPAddress resolves to the correct fully qualified DNS of the computer that is running SQL Server, the client side resolution is also successful.

SQL Server Service Principal Name creation

This is one of the critical parts of Kerberos and SQL Server interaction. With SQL Server, you can run the SQL Server service under one of the following: a LocalSystem account, a local user account, or a domain user account. When the SQL Server service instance starts, it tries to register its own SPN in Active Directory by using the DsWriteAccountSpn API call. If the call is not successful, the following warning is logged in Event Viewer:

Source: MSSQLServer EventID: 19011 Description: SuperSocket info: (SpnRegister) : Error 8344.

For more information about the DsWriteAccountSpn function, visit the following Microsoft Web site:

http://msdn2.microsoft.com/en-us/library/ms676056.aspx

Simplified explanation

If you run the SQL Server service under the LocalSystem account, the SPN is automatically registered and Kerberos interacts successfully with the computer that is running SQL Server. However, if you run the SQL Server service under a domain account or under a local account, the attempt to create the SPN will fail in most cases because the domain account and the local account do not have the right to set their own SPNs. When the SPN creation is not successful, this means that no SPN is set up for the computer that is running SQL Server. If you test using a domain administrator account as the SQL Server service account, the SPN is successfully created because the domain administrator-level credentials that you must have to create an SPN are present.

Because you might not use a domain administrator account to run the SQL Server service (to prevent security risk), the computer that is running SQL Server cannot create its own SPN. Therefore, you must manually create an SPN for your computer that is running SQL Server if you want to use Kerberos when you connect to a computer that is running SQL Server. This is true if you are running SQL Server under a domain user account or under a local user account. The SPN you create must be assigned to the service account of the SQL Server service on that particular computer. The SPN cannot be assigned to the computer container unless the computer that is running SQL Server starts with local system. There must be one and only one SPN, and it must be assigned to the appropriate container. Typically, this is the current SQL Server service account. However, this is the computer account with local system.

Verify the domain

Verify that the domain to which you log on can communicate with the domain to which the computer that is running SQL Server belongs. There must also be proper name resolution in the domain.

  1. You must make sure that you can successfully log on to Windows by using the same domain account and password as the startup account of the SQL Server service. For example, the SSPI error may occur in one of the following situations:
  • The domain account is locked out.
  • The password of the account was changed. However, you never restart the SQL Server service after the password was changed.

2. If your logon domain is different from the domain of the computer that is running SQL Server, check the trust relationship between the domains.

3. Check whether the domain that the server belongs to and the domain account that you use to connect are in the same forest. This is required for SSPI to work.

4. Use the Account is Trusted for Delegation option in Active Directory Users and Computers when you start SQL Server.

Note The ‘Account is Trusted for Delegation’ right is only required when you are delegating credentials from the target SQL server to a remote SQL server such as in a double hop scenario like distributed queries (linked server queries) that use Windows authentication.

5. Use the Manipulate Service Principal Names for Accounts (SetSPN.exe) utility in the Windows 2000 Resource Kit. Windows 2000 domain administrator accounts or Windows 2003 domain administrator accounts can use the utility to control the SPN that is assigned to a service and an account. In the case of SQL Server, there must be one and only one SPN. The SPN must be assigned to the appropriate container, the current SQL Server service account in most cases and the computer account when SQL Server starts with the local system account. If you start SQL Server while logged on with the LocalSystem account, the SPN is automatically set up. However, if you use a domain account to start SQL Server, or whenever you change the account that is used to start SQL Server, you must run SetSPN.exe to remove expired SPNs, and then you must add a valid SPN. For additional information, see the "Security Account Delegation" topic in SQL Server 2000 Books Online. To do so, visit the following Microsoft Web site:

http://msdn2.microsoft.com/en-us/library/aa905162(SQL.80).aspx

For more information about Windows 2000 Resource Kits, visit the following Microsoft Web site:

http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/default.mspx?mfr=true

6. Verify that name resolution is occurring correctly. Name resolution methods may include DNS, WINS, HOSTS files, and LMHOSTS files. For more information about name resolution problems and troubleshooting, click the following article number to view the article in the Microsoft Knowledge Base:

169790 How to troubleshoot basic TCP/IP problems

7. For more information about how to troubleshoot accessibility and firewall issues with Active Directory, click the following article numbers to view the articles in the Microsoft Knowledge Base:

291382 Frequently asked questions about Windows 2000 DNS and Windows Server 2003 DNS

224196 Restricting Active Directory replication traffic and client RPC traffic to a specific port

How to configure the SQL Server service to create SPNs dynamically for the SQL Server instances

To configure the SQL Server service to create SPNs dynamically, you must modify the account’s access control settings in the Active Directory directory service. You must grant the "Read servicePrincipalName" permission and the "Write servicePrincipalName" permission for the SQL Server service account.

Warning If you use the Active Directory Service Interfaces (ADSI) Edit snap-in, the LDP utility, or any other LDAP version 3 clients and you incorrectly modify the attributes of Active Directory objects, you can cause serious problems. These problems may require that you reinstall Microsoft Windows Server 2003, Microsoft Windows 2000 Server, Microsoft Exchange Server 2003, Microsoft Exchange 2000 Server, or both Windows and Exchange. We cannot guarantee that problems caused by incorrectly modifying the attributes of Active Directory objects can be resolved. Modify these attributes at your own risk.

Note To grant the appropriate permissions and user rights to the SQL Server startup account, you must be logged on as a domain administrator, or you must ask your domain administrator to do this task.

To configure the SQL Server service to create SPNs dynamically, follow these steps:

  1. Click Start, click Run, type Adsiedit.msc, and then click OK.
  2. In the ADSI Edit snap-in, expand Domain [DomainName], expand DC=RootDomainName, expand CN=Users, right-click CN=AccountName, and then clickProperties.

    Notes

  • DomainName is a placeholder for the name of the domain.
  • RootDomainName is a placeholder for the name of the root domain.
  • AccountName is a placeholder for the account that you specify to start the SQL Server service.
  • If you specify the Local System account to start the SQL Server service, AccountNameis a placeholder for the account that you use to log on to Microsoft Windows.
  • If you specify a domain user account to start the SQL Server service, AccountName is a placeholder for the domain user account.

3. In the CN=AccountNameProperties dialog box, click the Security tab.

4. On the Security tab, click Advanced.

5. In the Advanced Security Settings dialog box, make sure that SELF is listed underPermission entries.

If SELF is not listed, click Add, and then add SELF.

6. Under Permission entries, click SELF, and then click Edit.

7. In the Permission Entry dialog box, click the Properties tab.

8. On the Properties tab, click This object only in the Apply onto list, and then make sure that the check boxes for the following permissions are selected under Permissions:

o Read servicePrincipalName

o Write servicePrincipalName

9. Click OK three times, and then exit the ADSI Edit snap-in.

For help with this process, contact Active Directory product support, and mention this Microsoft Knowledge Base article.

Verify the server environment

Check some basic settings on the computer where SQL Server is installed:

  1. Kerberos is not supported on Windows 2000-based computers that are running Windows Clustering unless you have applied Service Pack 3 (or later) to Windows 2000. Therefore any attempt to use SSPI authentication on a clustered instance of SQL Server might not succeed. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

235529 Kerberos support on Windows 2000-based server clusters

2. Verify that the server is running Windows 2000 Service Pack 1 (SP1). For more information about Kerberos support on Windows 2000-based servers, click the following article number to view the article in the Microsoft Knowledge Base:

267588 "Cannot generate SSPI context" error message is displayed when you connect to SQL Server 2000

3. On a cluster, if the account that you use to start SQL Server, SQL Server Agent, or full-text search services changes, such as a new password, follow the steps that are provided in the following Microsoft Knowledge Base article:

239885 How to change service accounts for a clustered computer that is running SQL Server

4. Verify if the account that you use to start SQL Server has the appropriate permissions. If you are using an account that is not a member of the Local Administrators group, see the "Setting up Windows Services Accounts" topic in SQL Server Books Online for a detailed list of permissions that this account must have:

http://msdn2.microsoft.com/en-us/library/aa176564(SQL.80).aspx

Verify the client environment

Verify the following on the client:

  1. Make sure that the NTLM Security Support Provider is correctly installed and enabled on the client. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

269541 Error message when you connect to SQL Server if the Windows NT LM Security Support Provider registry key is missing: "cannot generate SSPI context"

2. Determine if you are using cached credentials. If you are logged on to the client with cached credentials, log off the computer and then log back on when you can connect to a domain controller to prevent the cached credentials from being used. For more information about how to determine if you are using cached credentials, click the following article number to view the article in the Microsoft Knowledge Base:

242536 User is not alerted when logging on with domain cached credentials

3. Verify that the dates on the client and the server are valid. If the dates are too far apart, your certificates may be considered invalid.

4. SSPI uses a file named Security.dll. If any other application installs a file with this name, the other file may be used instead of the actual SSPI file. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

253577 Error: 80004005 – MS ODBC SQL Server driver cannot initialize SSPI package

5. If the operating system on the client is Microsoft Windows 98, you must install the Client for Microsoft Networks component on the client. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

267550 BUG: "Assertion failed" when you connect to a SQL Server through TCP/IP

Verify the client network utility

The Client Network Utility (CNU) is delivered together with Microsoft Data Access Components (MDAC) and it is used to configure connectivity to computers that are running SQL Server. You can use the MDAC Cliconfg.exe CNU utility to configure connectivity:

  1. On the General tab, the way protocols are defined varies according to the MDAC version. With earlier versions of MDAC, you can select a "default" protocol. On the latest versions of MDAC, you can enable one or more protocols with one at the top of the list when you connect to SQL Server. Because SSPI applies only to TCP/IP, you can use a different protocol, such as Named Pipes, to avoid the error.
  2. Check the Alias tab in the CNU to verify if an alias has been defined for the server that you are trying to connect. If a server alias has been defined, check the settings for how this computer is configured to connect to SQL Server. You can verify this by deleting the alias server to see if the behavior changes.
  3. If the alias server is not defined on CNU, add the alias for the server that you are connecting to. When you perform this task, you are also explicitly defining the protocol and optionally defining the IP address and the port.

Information to collect to open a Microsoft Product Support (PSS) case

If you cannot obtain the cause of the problem by using the troubleshooting steps in this article, collect the following information and open a Microsoft Product Support (PSS) case:

For a complete list of Microsoft Product Support Services phone numbers and information about support costs, visit the following Microsoft Web site:

http://support.microsoft.com/contactus/?ws=support

1. Generate a sqldiag report from SQL Server. For more information, see the "sqldiag Utility" topic in SQL Server Books Online.

2. Capture a screenshot of the error on the client.

3. On the node that cannot connect to SQL Server, type the following command from the command prompt:

net start > started.txt

This command generates a file named Started.txt in the directory where you run the command.

4. Save the values for the registry key under the following registry key on your client computer:

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\MSSQLSERVER\CLIENT\CONNECTTO

5. In a clustered environment, get the value of following registry key for each node of the cluster:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA\LMCompatibilityLevel

6. In a clustered environment, see if the following registry key exists on each cluster server node:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTLMSsp

7. Capture the results if you connect to SQL Server by using a Universal Naming Convention (UNC) name (or the SQL Network Name on a cluster) from the client.

8. Capture the results if you ping the computer name (or the SQL Network Name on a cluster) from the client.

9. Save the name of the user accounts you use to start each one of the SQL Server services (MSSQLServer, SQLServerAgent, MSSearch).

10. The support professional must know whether SQL Server is configured for Mixed Authentication or Windows Only Authentication.

11. See if you can connect to the computer that is running SQL Server from the same client by using SQL Server Authentication.

12. See if you can connect by using Named Pipes protocol.

How to manually set up a Service Principal Name for SQL Server

For more information about how to manually set up a Service Principal Name for SQL Server, click the following article number to view the article in the Microsoft Knowledge Base:

319723 How to use Kerberos authentication in SQL Server

The Security Support Provider Interface (SSPI) is the interface to Microsoft Windows NT security that is used for Kerberos authentication, and supports the authentication scheme of the NTLM Security Support Provider. Authentication occurs at the operating system level when you log on to a Windows domain. Kerberos authentication is only available on Windows 2000-based computers that have Kerberos enabled and that are using Active Directory.

SSPI is only used for TCP/IP connections that are made by using Windows Authentication. (Windows Authentication is also known as Trusted Connections or Integrated Security.) SSPI is not used by Named Pipes or multi-protocol connections. Therefore, you can avoid the problem by configuring your clients to connect from a protocol other than TCP/IP.

When a SQL Server client tries to use integrated security over TCP/IP sockets to a remote computer that is running SQL Server, the SQL Server client network library uses the SSPI API to perform security delegation. The SQL Server network client (Dbnetlib.dll) makes a call to theAcquireCredentialsHandle function and passes in "negotiate" for the pszPackage parameter. This notifies the underlying security provider to perform negotiate delegation. In this context, negotiate means to try either Kerberos or NTLM authentication on Windows-based computers. In other words, Windows use Kerberos delegation if the destination computer that is running SQL Server has an associated, correctly configured SPN. Otherwise, Windows use NTLM delegation.

Note Verify that you are not using an account named "SYSTEM" to start any of the SQL Server services (MSSQLServer, SQLServerAgent, MSSearch). The keyword SYSTEM may cause conflicts with the Key Distribution Center (KDC).

Posted in Common | 3 Comments »

Understanding Kerberos and NTLM authentication in SQL Server Connections

Posted by Simon Cho on 04/26/2011

Understanding Kerberos and NTLM authentication in SQL Server Connections

http://blogs.msdn.com/b/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx

SQL Linked Server Query failed with “Login failed for user …"

http://blogs.msdn.com/b/sql_protocols/archive/2006/08/10/694657.aspx

Posted in Common | Leave a Comment »

How to make sure that you are using Kerberos authentication when you create a remote connection to an instance of SQL Server 2005

Posted by Simon Cho on 04/26/2011

http://support.microsoft.com/kb/909801/

How to register an SPN in a domain

When you register an SPN for a SQL Server service, you essentially create a mapping between an SPN and the Windows account that started the server instance service.

You must register the SPN because the client must use a registered SPN to connect to the server instance. The SPN is composed by using the server’s computer name and the TCP/IP port. If you do not register the SPN, the SSPI cannot determine the account that is associated with the SPN. Therefore, Kerberos authentication will not be used.

When SQL Server is running under the local system account or under a domain administrator account, the instance will automatically register the SPN in the following format when the instance starts:

MSSQLSvc/FQDN:tcpport

NoteFQDN is the fully qualified domain name of the server. tcpport is the TCP/IP port number.

Because the TCP port number is included in the SPN, SQL Server must enable the TCP/IP protocol for a user to connect by using Kerberos authentication. The same rules apply for clustered configurations. Additionally, if the instance automatically registered an SPN when the instance started, the SPN will be unregistered automatically when the instance stops.

Only a domain administrator account or the local system account has the required permissions to register an SPN. Therefore, if the SQL Server service is started under a non-administrator account, SQL Server cannot register the SPN for the instance. This behavior will not prevent the instance from starting. However, the following message will be logged in the Application log of the Windows event log:

Event Type: Information
Event Source: MSSQL$InstanceName
Event Category: (2)
Event ID: 26037
Date: Date
Time: Time
User: N/A
Computer: ComputerName
Description:
The SQL Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service. Error: 0x54b. Failure to register an SPN may cause integrated authentication to fall back to NTLM instead of Kerberos. This is an informational message. Further action is only required if Kerberos authentication is required by authentication policies.
For more information, see Help and Support Center at http://support.microsoft.com.

If this message is logged, you must manually register the SPN for the instance under a domain administrator account to use Kerberos authentication. To register the SPN, you can use the SetSPN.exe tool that is included with the Microsoft Windows 2000 Server Resource Kit. This tool is also included with the Microsoft Windows Server 2003 Support Tools. The Windows Server 2003 Support Tools are included in Microsoft Windows Server 2003 Service Pack 1 (SP1).

For more information about how to obtain the Windows Server 2003 Service Pack 1 Support Tools, click the following article number to view the article in the Microsoft Knowledge Base:

892777 Windows Server 2003 Service Pack 1 Support Tools

You can use a command that is similar to the following to register an SPN for an instance:

SetSPN –A MSSQLSvc/<ComputerName>.<DomainName>:1433 <AccountName>

Note If an SPN already exists, you must delete the SPN before you can reregister it. You may have to do this if the account mapping has changed. To deleted an existing SPN, you can use the SetSPN.exe tool together with the -D switch.

How to make sure that you are using Kerberos authentication

After you connected to an instance of SQL Server 2005, run the following Transact-SQL statement in SQL Server Management Studio:

select auth_scheme from sys.dm_exec_connections where session_id=@@spid

If SQL Server is using Kerberos authentication, a character string that is listed as "KERBEROS" appears in the auth_scheme column in the result window.

Posted in Common | Leave a Comment »

Kerberos error event logging

Posted by Simon Cho on 04/26/2011

http://support.microsoft.com/kb/262177

Enabling Kerberos Event Logging on a Specific Computer

1. Start Registry Editor.

2. Add the following registry value:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters

Registry Value: LogLevel
Value Type: REG_DWORD
Value Data: 0x1

If the Parameters subkey does not exist, create it.

Note Remove this registry value when it is no longer needed so that performance is not degraded on the computer. Also, you can remove this registry value to disable Kerberos event logging on a specific computer.

3. Quit Registry Editor. The setting will become effective immediately on Windows Server 2008, on Windows Vista, on Windows Server 2003, and on Windows XP. For Windows 2000, you must restart the computer.

You can find any Kerberos-related events in the system log.

Posted in Common | Leave a Comment »

SQL Nexus for SQL 2008 R2 x64

Posted by Simon Cho on 04/12/2011

1. There are no PerfStats for SQL 2008 R2.

for that you need to modified XML file.

<Instance name="*" windowsauth="true" ssver="10" user="">

to

<Instance name="*" windowsauth="true" ssver="10.5" user="">

SQL Server 2008R2 =10.5

SQL Server 2008 =10

SQL Server 2005 =9

2. x64 issue for RML

Try these steps:
1) go to add/remove programs and uninstall old RML program
2) then download latest http://www.microsoft.com/downloads/details.aspx?familyid=7EDFA95A-A32F-440F-A3A8-5160C8DBE926&displaylang=en and install it. this should over-write the registry key to use the latest.
3) If you had installed http://www.microsoft.com/downloads/details.aspx?familyid=7EDFA95A-A32F-440F-A3A8-5160C8DBE926&displaylang=en, go to C:\Program Files\Microsoft Corporation\RMLUtils and do orca.exe /R from there.
note that this assumes you are using 32 bit. if you are on x64, you need to download 64 bit readtrace

Posted in Common | Leave a Comment »

SQL Server Trace Flags

Posted by Simon Cho on 04/12/2011

lag Trace Flag Description (underlined are sp_configure’able)
-1 Sets trace flags for all connections. Used only with DBCC TRACEON and TRACEOFF. The setting of the Trace flag -1 is not visible with DBCC TRACESTATUS command, but work without problems.
105 SQL Server 6.5 you can use maximum 16 tables or subqueries in a single select statement. There is no documented way, to avoid this restriction, but you can use undocumented trace flag 105 for this purpose.
106 Disables line number information for syntax errors.
107 Interprets numbers with a decimal point as float instead of decimal.
110 Turns off ANSI select characteristics.
204 A backward compatibility switch that enables non-ansi standard behavior. E.g. previously SQL server ignored trailing blanks in the like statement and allowed queries that contained aggregated functions to have items in the group by clause that were not in the select list.
205 Report when a statistics-dependent stored procedure is being recompiled as a result of AutoStat.
206 Provides backward compatibility for the setuser statement.
208 SET QUOTED IDENTIFIER ON.
237 Tells SQL Server to use correlated sub-queries in Non-ANSI standard backward compatibility mode.
242 Provides backward compatibility for correlated subqueries where non-ANSI-standard results are desired.
243 The behavior of SQL Server is now more consistent because null ability checks are made at run time and a null ability violation results in the command terminating and the batch or transaction process continuing.
244 Disables checking for allowed interim constraint violations. By default, SQL Server checks for and allows interim constraint violations. An interim constraint violation is caused by a change that removes the violation such that the constraint is met, all within a single statement and transaction. SQL Server checks for interim constraint violations for self-referencing DELETE statements, INSERT, and multi-row UPDATE statements. This checking requires more work tables. With this trace flag you can disallow interim constraint violations, thus requiring fewer work tables.
246 Derived or NULL columns must be explicitly named in a select….INTO or create view statement when not done they raise an error. This flag avoids that.
253 Prevents ad-hoc query plans to stay in cache.
257 Will invoke a print algorithm on the XML output before returning it to make the XML result more readable.
260 Prints versioning information about extended stored procedure dynamic-link libraries (DLLs). For more information about __GetXpVersion(), see Creating Extended Stored Procedures. Scope: global or session
262 SQL 7 – Trailing spaces are no longer truncated from literal strings in CASE statements. Used after hotfix 891116
302 Should be used with flag 310 to show the actual join ordering. Prints information about whether the statistics page is used, the actual selectivity (if available), and what SQL Server estimated the physical and logical I/O would be for the indexes.
310 Prints information about join order. Index selection information is also available in a more readable format using SET SHOWPLAN_ALL, as described in the SET statement.
320 Disables join-order heuristics used in ANSI joins. To see join-order heuristics use flag 310. SQL Server uses join-order heuristics to reduce the no’ of permutations when using the best join order.
323 Reports on the use of update statements using UPDATE in place. Shows a detailed description of the various update methods used by SQL Server 6.5.
325 Prints information about the cost of using a non-clustered index or a sort to process an ORDER BY clause.
326 Prints information about the estimated & actual costs of sorts. Instructs the server to use arithmetic averaging when calculating density instead of a geometric weighted average when updating statistics.  Useful for building better stats when an index has skew on the leading column.  Use only for updating the stats of a table/index with known skewed data.
330 Enables full output when using the SET SHOWPLAN_ALL option, which gives detailed information about joins.
342 Disables the costing of pseudo-merge joins, thus significantly reducing time spent on the parse for certain types of large, multi-table joins. One can also use SET FORCEPLAN ON to disable the costing of pseudo-merge joins because the query is forced to use the order specified in the FROM clause.
345 Increase the accuracy of choice of optimum order when you join 6 or more tables.
506 Enforces SQL-92 standards regarding null values for comparisons between variables and parameters. Any comparison of variables and parameters that contain a NULL always results in a NULL.
610 SQL 10 – Enable the potential for minimal-logging when:
·   Bulk loading into an empty clustered index, with no nonclustered indexes
·   Bulk loading into a non-empty heap, with no nonclustered indexes
611 After SQL 9 when turned on, each lock escalation is recorded in the SQL Server error log along with the SQL Server handle number.
652 Disables read ahead for the server.
653 Disables read ahead for the current connection.
661 Disables the ghost record removal process. A ghost record is the result of a delete operation. When you delete a record, the deleted record is kept as a ghost record. Later, the deleted record is purged by the ghost record removal process. When you disable this process, the deleted record is not purged. Therefore, the space that the deleted record consumes is not freed. This behavior affects space consumption and the performance of scan operations. SCOPE: Global. If you turn off this trace flag, the ghost record removal process works correctly.
806 Cause ‘DBCC-style’ page auditing to be performed whenever a database page is read into the buffer pool. This is useful to catch cases where pages are being corrupted in memory and then written out to disk with a new page checksum. When they’re read back in the checksum will look correct, but the page is corrupt (because of the previous memory corruption). This page auditing goes someway to catching this – especially on non-Enterprise Edition systems that don’t have the ‘checksum sniffer’.
809 SQL 8 – Limits the amount of Lazy Write activity.
815 Enables latch enforcement. SQL Server 8 (with service pack 4) and SQL Server 9 can perform latch enforcement for data pages found in the buffer pool cache. Latch enforcement changes the virtual memory protection state while database page status changes from “clean” to “dirty” (“dirty” means modified through INSERT, UPDATE or DELETE operation). If an attempt is made to modify a data page while latch enforcement is set, it causes an exception and creates a mini-dump in SQL Server installation’s LOG directory. Microsoft support can examine the contents of such mini-dump to determine the cause of the exception. In order to modify the data page the connection must first acquire a modification latch. Once the data modification latch is acquired the page protection is changed to read-write. Once the modification latch is released the page protection changes back to read-only.
818 SQL 8 enables in memory ring buffer used to track last 2048 successful write operations.
830 SQL 9 – disable the reporting of CPU Drift errors in the SQL Server errorlog like SQL Server has encountered 2 occurrence(s) of I/O requests taking longer than 15 seconds to complete
834 Causes SQL Server to use Windows large-page allocations for the memory that is allocated for the buffer pool. The page size varies depending on the hardware platform, but the page size may be from 2 MB to 16 MB. Large pages are allocated at startup and are kept throughout the lifetime of the process. Trace flag 834 improves performance by increasing the efficiency of the translation look-aside buffer (TLB) in the CPU.
Flag 834 applies only to 64-bit versions of SQL Server. You must have the Lock pages in memory user right to turn on trace flag 834. You can turn on trace flag 834 only at startup.
Trace flag 834 may prevent the server from starting if memory is fragmented and if large pages cannot be allocated. Therefore, trace flag 834 is best suited for servers that are dedicated to SQL Server.
For more information about large-page support, http://msdn2.microsoft.com/en-us/library/aa366720.aspx(http://msdn2.microsoft.com/en-us/library/aa366720.aspx)
835 SQL 9 & 10. For 64 bit SQL Server. This turns off Lock pages in memory.
836 Causes SQL Server to size the buffer pool at startup based on the value of the max server memory option instead of based on the total physical memory. You can use trace flag 836 to reduce the number of buffer descriptors that are allocated at startup in 32-bit Address Windowing Extensions (AWE) mode.
Trace flag 836 applies only to 32-bit versions of SQL Server that have the AWE allocation enabled. You can turn on trace flag 836 only at startup.
845 SQL 9 & 10. For 64 bit SQL Server. This turns on Lock pages in memory.
1117 Grows all data files at once, else it goes in turns.
1118 Switches allocations in tempDB from 1pg at a time (for first 8 pages) to one extent. There is now a cache of temp tables. When a new temp table is created on a cold system it uses the same mechanism as for SQL 8. When it is dropped though, instead of all the pages being deallocated completely, one IAM page & one data page are left allocated, then the temp table is put into a special cache. Subsequent temp table creations will look in the cache to see if they can just grab a pre-created temp table. If so, this avoids accessing the allocation bitmaps completely. The temp table cache isn’t huge (32 tables), but this can still lead to a big drop in latch contention in tempdb. http://www.sqlskills.com/BLOGS/PAUL/post/Misconceptions-around-TF-1118.aspx
1180 Forces allocation to use free pages for text or image data and maintain efficiency of storage. 1197 applies only in the case of SQL 7 – SP3. Helpful in case when DBCC SHRINKFILE and SHRINKDATABASE commands may not work because of sparsely populated text, ntext, or image columns
1197
1200 Prints lock information (the process ID and type of lock requested).
1202 Insert blocked lock requests into syslocks.
1204 Returns resources and types of locks participating in a deadlock and command affected. Scope: global only
1205 More detailed information about the command being executed at the time of a deadlock. This trace flag was documented in SQL Server 7.0 Books Online, but was not documented in SQL Server 8.
1206 Used to complement flag 1204 by displaying other locks held by deadlock parties
1211 Disables lock escalation based on memory pressure, or based on number of locks. The SQL Server Database Engine will not escalate row or page locks to table locks.
Using this trace flag can generate excessive numbers of locks. This can slow the performance of the Database Engine, or cause 1204 errors (unable to allocate lock resource) because of insufficient memory. For more information, see Lock Escalation (Database Engine).
If both trace flag 1211 and 1224 are set, 1211 takes precedence over 1224. However, because trace flag 1211 prevents escalation in every case, even under memory pressure, we recommend that you use 1224. This helps avoid “out-of-locks” errors when many locks are being used. Scope: global or session
1216 SQL 7 – Disables Health reporting. Lock monitor when detects a (worker thread) resource level blocking scenario. If a SPID that owns a lock is currently queued to the scheduler, because all the assigned worker threads have been created and all the assigned worker threads are in an un-resolvable wait state, the following error message is written to the SQL Server error log:
Error 1223: Process ID %d:%d cannot acquire lock “%s” on resource %s because a potential deadlock exists on Scheduler %d for the resource. Process ID %d:% d holds a lock “%h” on this resource.
1222 Returns the resources and types of locks that are participating in a deadlock and also the current command affected, in an XML format that does not comply with any XSD schema. Scope: global only
1224 Disables lock escalation based on the number of locks. However, memory pressure can still activate lock escalation. The Database Engine escalates row or page locks to table (or partition) locks if the amount of memory used by lock objects exceeds one of the following conditions:
·   40% of the memory that is used by Db Engine, exclusive of memory allocation using Address Windowing Extension (AWE). This is applicable when the locks parameter of sp_configure is set to 0.
·   Forty percent of the lock memory that is configured by using the locks parameter of sp_configure.
If both trace flag 1211 and 1224 are set, 1211 takes precedence over 1224. However, because trace flag 1211 prevents escalation in every case, even under memory pressure, we recommend that you use 1224. This helps avoid “out-of-locks” errors when many locks are being used.
Note:Lock escalation to the table- or HoBT-level granularity can also be controlled by using the LOCK_ESCALATION option of the ALTER TABLE statement.  Scope:global or session
1261 SQL 8 – Disables Health reporting. Lock monitor when detects a (worker thread) resource level blocking scenario. If a SPID that owns a lock is currently queued to the scheduler, because all the assigned worker threads have been created and all the assigned worker threads are in an un-resolvable wait state, the following error message is written to the SQL Server error log:
Error 1229: Process ID %d:%d owns resources that are blocking processes on scheduler %d.
1400 Enables the creation of the database mirroring endpoint, which is required for setting up and using database mirroring. This trace flag is allowed only when using the –T.
1462 Turns off log stream compression and effectively reverts the behavior back to ver 9.
1603 Use standard disk I/O (i.e. turn off asynchronous I/O).
1609 Turns on the unpacking and checking of remote procedure call (RPC) information in Open Data Services. Used only when applications depend on the old behavior.
1610 Boot the SQL dataserver with TCP_NODELAY enabled.
1611 If possible, pin shared memory — check errorlog for success/failure.
1704 Prints information when a temporary table is created or dropped.
1717 Causes new objects being created to be system objects.
1806 Disables instant file initialization.
1807 Allows creating a database file on a mapped or UNC network location. unsupported under SQL Server 7 & 8.
2301 Enables advanced optimizations that are specific to decision support queries. This option applies to decision support processing of large data sets.
2330 Stops the collection of statistics for sys.db_index_usage_stats.
2382 Statistics collected for system tables.
2389 SQL 9 – Tracks the nature of columns by subsequent statistics updates. When SQL Server determines that the statistics increase three times, the column is branded ascending. The statistics will be updated automatically at query compile.
2390 Does the same like 2389 even if ascending nature of the column is not known and — never enable without 2389.
2440 Parallel query execution strategy on partitioned tables. SQL 9 – uses a single thread per partition parallel query execution strategy. In ver. 10, multiple threads can be allocated to a single partition, thus improving the query’s response time.
2505 Prevents DBCC TRACEON 208, SPID 10 errors from appearing in the error log.
2508 Disables parallel non-clustered index checking for DBCC CHECKTABLE.
2509 Used with DBCC CHECKTABLE.html to see the total count of ghost records in a table
2520 Force DBCC HELP to return syntax of undocumented DBCC statements. If 2520 is not turned on, DBCC HELP will refuse to give you the syntax stating: “No help available for DBCC statement ‘undocumented statement'”.
2528 Disables parallel checking of objects by DBCC CHECKDB, CHECKFILEGROUP and CHECKTABLE. By default, the degree of parallelism is automatically determined by the query processor. The maximum degree of parallelism is configured just like that of parallel queries. For more information, see max degree of parallelism Option.
Parallel DBCC should typically be left enabled. For DBCC CHECKDB, the query processor reevaluates and automatically adjusts parallelism with each table or batch of tables checked. Sometimes, checking may start when the server is almost idle. An administrator who knows that the load will increase before checking is complete may want to manually decrease or disable parallelism.
Disabling parallel checking of DBCC can cause it to take much longer to complete and if DBCC is run with the TABLOCK feature enabled and parallelism set off, tables may be locked for longer periods of time.
Scope: global or session
2537 SQL 9 & 10. Allows function ::fn_dblog to look inside all logs (not just the active log).
2542 SQL 8 – Used with Sqldumper.exe to get certain dumps. In range 254x – 255x.
2551 Adds additional information to the dump file.
2701 Sets the @@ERROR system function to 50000 for RAISERROR messages with severity levels of 10 or less. When disabled, sets the @@ERROR system function to 0 for RAISERROR messages with severity levels of 10 or less.
2861 Cache query plans for queries that have a cost of zero or near to zero.
3001 Stops sending backup entries into MSDB.
3004 Gives out more detailed information about restore & backup activities.
3031 SQL 9 – will turn the NO_LOG and TRUNCATE_ONLY options into checkpoints in all recovery modes.
3104 Causes SQL Server to bypass checking for free space.
3111 Cause LogMgr::ValidateBackedupBlock to be skipped during backup and restore operations.
3205 If a tape drive supports hardware compression, either the DUMP or BACKUP statement uses it. With this trace flag, you can disable hardware compression for tape drivers. This is useful when you want to exchange tapes with other sites or tape drives that do not support compression. Scope: global or session
3213 Trace SQL Server activity during backup process so that we will come to know which part of backup process is taking more time.
3222 Disables the read ahead that is used by the recovery operation during roll forward operations.
3226 With this trace flag, you can suppress BACKUP COMPLETED log entries going to WIN and SQL logs.
3231 SQL 8 & 9 – will turn the NO_LOG and TRUNCATE_ONLY options into no-ops in FULL/BULK_LOGGED recovery mode, and will clear the log in SIMPLE recovery mode.
3282 SQL 6.5 – Used after backup restoration fails refer to microsoft for article Q215458.
3422 Cause auditing of transaction log records as they’re read (during transaction rollback or log recovery). This is useful because there is no equivalent to page checksums for transaction log records and so no way to detect whether log records are being corrupted e careful with these trace flags – I don’t recommend using them unless you are experiencing corruptions that you can’t diagnose. Turning them on will cause a big CPU hit because of the extra auditing that’s happening.
3502 Tracks CHECKPOINT – Prints a message to the log at the start and end of each checkpoint.
3503 Indicates whether the checkpoint at the end of automatic recovery was skipped for a database (this applies only to read-only databases).
3504 For internal testing. Will raise a bogus log-out-of-space condition from checkpoint()
3505 Disables automatic checkpoints. May increase recovery time and can prevent log space reuse until the next checkpoint is issued. Make sure to issue manual checkpoints on all read/write databases at appropriate time intervals.
Note does not prevent the internal checkpoints that are issued by certain commands, such as BACKUP.
3601 Stack trace when error raised. Also see 3603
3602 Records all error and warning messages sent to the client.
3603 SQL Server fails to install on tricore, Bypass SMT check is enabled, flags are added via registry. Also see 3601.
3604 Sends trace output to the client. This trace flag is used only when setting trace flags with DBCC TRACEON and DBCC TRACEOFF.
3605 Sends trace output to the error log.  (if SQL Server is started from CMD output also appears on the screen)
3607 Trace flag 3607 skips the recovery of databases on the startup of SQL Server and clears the TempDB. Setting this flag lets you get past certain crashes, but there is a chance that some data will be lost
3608 Prevents SQL Server from automatically starting and recovering any database except the master database. Databases will be started and recovered when accessed. Some features, such as snapshot isolation and read committed snapshot, might not work.
3609 Skips the creation of the tempdb database at startup. Use this trace flag if the device or devices on which tempdb resides are problematic or problems exist in the model database.
3610 SQL 9. Divide by zero to result in NULL instead of error.
3625 Limits the amount of information returned in error messages. For more information, see Metadata Visibility Configuration. Scope: global only
3626 Turns on tracking of the CPU data for the sysprocesses table.
3640 Eliminates the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. This is similar to the session setting of SET NOCOUNT ON, but when set as a trace flag, every client session is handled this way.
3689 Logs extended errors to errorlog when network disconnect occurs, turned off by default. Will dump out the socket error code this can sometimes give you a clue as to the root cause.
3913 SQL 7/8 – SQL Server does not update the rowcnt column of the sysindexes system table until the transaction is committed. When turned on the optimizer gets row count information from in-memory metadata that is saved to sysindexes system table when the transaction commits.
4013 This trace flag writes an entry to the SQL Server error log when a new connection is established. For each connection that occurs, the trace flag writes two entries that look like this:
Login: sa saSQL Query Analyzer(local)ODBCmaster, server process ID (SPID): 57, kernel process ID (KPID): 57.
Login: sa XANADUsaSQL Query Analyzer(local)ODBCmaster, server process ID (SPID): 57, kernel process ID (KPID): 57.
4022 If turns on, then automatically started procedures will be bypassed.
4029 Logs extended errors to errorlog when network disconnect occurs, turned off by default. Will dump out the socket error code this can sometimes give you a clue as to the root cause.
4030 Prints both a byte and ASCII representation of the receive buffer. Used when you want to see what queries a client is sending to SQL Server. You can use this trace flag if you experience a protection violation and want to determine which statement caused it. Typically, you can set this flag globally or use SQL Server Enterprise Manager. You can also use DBCC INPUTBUFFER.
4031 Prints both a byte and ASCII representation of the send buffers (what SQL Server sends back to the client). You can also use DBCC OUTPUTBUFFER.
4032 Traces the SQL commands coming in from the client. The output destination of the trace flag is controlled with the 3605/3604 trace flags.
4101 SQL 9 – Query that involves an outer join operation runs very slowly. However, if you use the FORCE ORDER query hint in the query, the query runs much faster. Additionally, the execution plan of the query contains the following text in theWarnings column:  NO JOIN PREDICATE
4121 Turn these trace flags after HOTFIX is applied (SP2 CUP4)
4606 Over comes SA password by startup. Refer to Ms article 936892.
4612 Disable the ring buffer logging – no new entries will be made into the ring buffer.
4613 Generate a minidump file whenever an entry is logged into the ring buffer.
4616 Makes server-level metadata visible to application roles. In SQL Server, an application role cannot access metadata outside its own database because application roles are not associated with a server-level principal. This is a change of behavior from earlier versions of SQL Server. Setting this global flag disables the new restrictions, and allows for application roles to access server-level metadata. Scope: global only
5302 Alters default behavior of select…INTO (and other processes) that lock system tables for the duration of the transaction. This trace flag disables such locking during an implicit transaction.
6527 Disables generation of a memory dump on the first occurrence of an out-of-memory exception in CLR integration. By default, SQL Server generates a small memory dump on the first occurrence of an out-of-memory exception in the CLR. The behavior of the trace flag is as follows:
·   If this is used as a startup trace flag, a memory dump is never generated. However, a memory dump may be generated if other trace flags are used.
·   If this trace flag is enabled on a running server, a memory dump will not be automatically generated from that point on. However, if a memory dump has already been generated due to an out-of-memory exception in the CLR, this trace flag will have no effect. Scope: global only
7103 Disable table lock promotion for text columns. Refer to Ms article – 230044
7300 Retrieves extended information about any error you encounter when you execute a distributed query.
7501 Dynamic cursors are used by default on forward-only cursors. Dynamic cursors are faster than in earlier versions and no longer require unique indexes. This flag disables the dynamic cursor enhancements and reverts to version 6.0 behavior.
7502 Disables the caching of cursor plans for extended stored procedures.
7505 Enables version 6.x handling of return codes when calling dbcursorfetchex and the resulting cursor position follows the end of the cursor result set.
7525 Reverts to the SQL Server 7 behavior of closing nonstatic cursors regardless of the SET CURSOR_CLOSE_ON_COMMIT state in SQL Server 8.
7601 Turns on full text indexing. Together these four gather more information about full text search (indexing process) to the error log.
7646 SQL 10. Avoids blocking when using full text indexing. An issue we experienced that full text can be slow when there is a high number of updates to the index and is caused by blocking on the docidfilter internal table.
7806 Enables a dedicated administrator connection (DAC) on SQL Svr Express. By default, no DAC resources are reserved on SQL Server Express.
8004 SQL server to create a mini dump once you enable 2551 and a out of memory condition is hit.
8011 Disables the collection of additional diagnostic information for Resource Monitor. You can use the information in this ring buffer to diagnose out-of-memory conditions. Scope: GLOBAL.
8012 Records an event in the schedule ring buffer every time that one of the following events occurs:
·   A scheduler switches context to another worker.
·   A worker is suspended or resumed.
·   A worker enters the preemptive mode or the non-preemptive mode.
You can use the diagnostic information in this ring buffer to analyze scheduling problems. For example, you can use the information in this ring buffer to troubleshoot problems when SQL Server stops responding.
Trace flag 8012 disables recording of event

 

Posted in Common | Leave a Comment »

Get SQL server version + port #

Posted by Simon Cho on 04/11/2011

http://www.sqlservercentral.com/Forums/Topic912647-2621-1.aspx


DECLARE @Server AS VARCHAR(128)

DECLARE @KeyToInterogate AS VARCHAR(200)

DECLARE @PortNumber AS VARCHAR(8)

SET @Server = @@SERVERNAME

SET @KeyToInterogate = ‘SOFTWARE\MICROSOFT\MSSQLSERVER\MSSQLSERVER\SUPERSOCKETNETLIB\TCP’

IF Charindex(‘\’,@@SERVERNAME) > 0

BEGIN

SET @KeyToInterogate = ‘SOFTWARE\Microsoft\Microsoft SQL Server\’

SET @KeyToInterogate = @KeyToInterogate + Substring(@@SERVERNAME,Charindex(‘\’,@@SERVERNAME) + 1,Len(@@SERVERNAME)  Charindex(‘\’,@@SERVERNAME))

SET @KeyToInterogate = @KeyToInterogate + ‘\MSSQLServer\SuperSocketNetLib\Tcp’

END

 

EXEC Xp_regread

@rootkey = ‘HKEY_LOCAL_MACHINE’,

@key = @KeyToInterogate,

@value_name = ‘TcpPort’,

@value = @PortNumber OUTPUT

SELECT @@SERVERNAME AS hostname

, Serverproperty(‘Edition’) AS edition

, Isnull(Serverproperty(‘InstanceName’),) AS instancename

, Serverproperty(‘MachineName’) AS machinename

, Serverproperty(‘ProductVersion’) AS productversion

, CASE

WHEN CONVERT(VARCHAR(255),Serverproperty(‘ProductVersion’)) LIKE ‘8.0%’ THEN ‘2000’

WHEN CONVERT(VARCHAR(255),Serverproperty(‘ProductVersion’)) LIKE ‘9.0%’ THEN ‘2005’

WHEN CONVERT(VARCHAR(255),Serverproperty(‘ProductVersion’)) LIKE ‘10.0%’ THEN ‘2008’

WHEN CONVERT(VARCHAR(255),Serverproperty(‘ProductVersion’)) LIKE ‘10.5%’ THEN ‘2008 R2’

END

, CAST(@PortNumber AS VARCHAR) AS portno

 

 

Simon Cho

Posted in Common | Leave a Comment »

article bug fixed when you editing SQL Agent Job

Posted by Simon Cho on 04/08/2011

http://support.microsoft.com/kb/2315727/

or

Traverse to the C:Program FilesMicrosoft SQL Server100DTSbinn directory and run the following from the command:

REGSVR32.EXE dts.dll

Posted in Common | Leave a Comment »

Performance issue with Data collection

Posted by Simon Cho on 04/06/2011

The new feature of Data collection has performance issue.

There is one job name as “mdw_purge_data_[db_datacollector]”

Basically, this procedure has 2 missing indexes.

And this job is for deleted orphaned records, so, it working with table scan for base table.

So, you should keep the small base table data.

That meaning is that setup the retention days as small as you can.!!

reference  : http://www.toddbaker.org/blog/2010/12/17/sql-2008-mdw-fixing-long-running-purges/

sp: exec core.sp_purge_data


USE [db_datacollector] 

GO

/****** Object:  StoredProcedure [core].[sp_purge_data]    Script Date: 04/06/2011 04:25:41 ******/

SET ansi_nulls ON

GO

SET quoted_identifier ON

GO

ALTER PROCEDURE [core].[Sp_purge_data] @retention_days SMALLINT = NULL,

@instance_name SYSNAME = NULL,

@collection_set_uid UNIQUEIDENTIFIER =

NULL,

@duration SMALLINT = NULL

AS

BEGIN

— Security check (role membership)

IF ( NOT ( Isnull(Is_member(N’mdw_admin’), 0) = 1 )

AND NOT ( Isnull(Is_srvrolemember(N’sysadmin’), 0) = 1 ) )

BEGIN

RAISERROR(14677,

16,

1,

‘mdw_admin’)

RETURN( 1 ) — Failure

END

— Validate parameters

IF ( ( @retention_days IS NOT NULL )

AND ( @retention_days < 0 ) )

BEGIN

RAISERROR(14200,

1,

1,

‘@retention_days’)

RETURN( 1 ) — Failure

END

IF ( ( @duration IS NOT NULL )

AND ( @duration < 0 ) )

BEGIN

RAISERROR(14200,

1,

1,

‘@duration’)

RETURN( 1 ) — Failure

END

— This table will contain a record if somebody requests purge to stop

— If user requested us to purge data – we reset the content of it – and proceed with purge

— If somebody in a different session wants purge operations to stop he adds a record

— that we will discover while purge in progress

— We dont clear this flag when we exit since multiple purge operations with differnet

— filters may proceed, and we want all of them to stop.

DELETE FROM [core].[purge_info_internal]

SET @instance_name = Nullif(Ltrim(Rtrim(@instance_name)), N”)

— Calculate the time when the operation should stop (NULL otherwise)

DECLARE @end_time DATETIME

IF ( @duration IS NOT NULL )

BEGIN

SET @end_time = Dateadd(MINUTE, @duration, Getutcdate())

END

— Declare table that will be used to find what are the valid

— candidate snapshots that could be selected for purge

DECLARE @purge_candidates TABLE (

snapshot_id INT NOT NULL,

snapshot_time DATETIME NOT NULL,

instance_name SYSNAME NOT NULL,

collection_set_uid UNIQUEIDENTIFIER NOT NULL )

— Find candidates that match the retention_days criteria (if specified)

IF ( @retention_days IS NULL )

BEGIN

— User did not specified a value for @retention_days, therfore we

— will use the default expiration day as marked in the source info

INSERT INTO @purge_candidates

SELECT s.snapshot_id,

s.snapshot_time,

s.instance_name,

s.collection_set_uid

FROM core.snapshots s

WHERE ( Getutcdate() >= s.valid_through )

END

ELSE

BEGIN

— User specified a value for @retention_days, we will use this overriden value

— when deciding what means old enough to qualify for purge this overrides

— the days_until_expiration value specified in the source_info_internal table

INSERT INTO @purge_candidates

SELECT s.snapshot_id,

s.snapshot_time,

s.instance_name,

s.collection_set_uid

FROM core.snapshots s

WHERE Getutcdate() >= Dateadd(DAY, @retention_days,

s.snapshot_time)

END

— Determine which is the oldest snapshot, from the list of candidates

DECLARE oldest_snapshot_cursor CURSOR FORWARD_ONLY READ_ONLY FOR

SELECT p.snapshot_id,

p.instance_name,

p.collection_set_uid

FROM @purge_candidates p

WHERE ( ( @instance_name IS NULL )

OR ( p.instance_name = @instance_name ) )

AND ( ( @collection_set_uid IS NULL )

OR ( p.collection_set_uid = @collection_set_uid ) )

ORDER BY p.snapshot_time ASC

OPEN oldest_snapshot_cursor

DECLARE @stop_purge INT

DECLARE @oldest_snapshot_id INT

DECLARE @oldest_instance_name SYSNAME

DECLARE @oldest_collection_set_uid UNIQUEIDENTIFIER

FETCH NEXT FROM oldest_snapshot_cursor INTO @oldest_snapshot_id,

@oldest_instance_name, @oldest_collection_set_uid

— As long as there are snapshots that matched the time criteria

WHILE @@FETCH_STATUS = 0

BEGIN

— Filter out records that do not match the other filter crieria

IF ( ( @instance_name IS NULL )

OR ( @oldest_instance_name = @instance_name ) )

BEGIN

— There was no filter specified for instance_name or the instance matches the filter

IF ( ( @collection_set_uid IS NULL )

OR ( @oldest_collection_set_uid = @collection_set_uid )

)

BEGIN

— There was no filter specified for the collection_set_uid or the collection_set_uid matches the filter

BEGIN TRANSACTION tran_sp_purge_data

— Purge data associated with this snapshot. Note: deleting this snapshot

— triggers cascade delete in all warehouse tables based on the foreign key

— relationship to snapshots table

— Cascade cleanup of all data related referencing oldest snapshot

DELETE core.snapshots_internal

FROM core.snapshots_internal s

WHERE s.snapshot_id = @oldest_snapshot_id

COMMIT TRANSACTION tran_sp_purge_data

PRINT ‘Snapshot #’ + CONVERT(NVARCHAR(MAX),

@oldest_snapshot_id)

+

‘ purged.’;

END

END

— Check if the execution of the stored proc exceeded the @duration specified

IF ( @duration IS NOT NULL )

BEGIN

IF ( Getutcdate() >= @end_time )

BEGIN

PRINT ‘Stopping purge. More than ‘ +

CONVERT(NVARCHAR(MAX), @duration)

+

‘ minutes passed since the start of operation.’;

BREAK

END

END

— Check if somebody wanted to stop the purge operation

SELECT @stop_purge = COUNT(stop_purge)

FROM [core].[purge_info_internal]

IF ( @stop_purge > 0 )

BEGIN

PRINT ‘Stopping purge. Detected a user request to stop purge.’

;

BREAK

END

— Move to next oldest snapshot

FETCH NEXT FROM oldest_snapshot_cursor INTO @oldest_snapshot_id,

@oldest_instance_name, @oldest_collection_set_uid

END

CLOSE oldest_snapshot_cursor

DEALLOCATE oldest_snapshot_cursor

— Delete orphaned rows from snapshots.notable_query_plan.  Query plans are not deleted by the generic purge

— process that deletes other data (above) because query plan rows are not tied to a particular snapshot ID.

— Purging query plans table and the smaller query text table as a special case, by looking for plans that

— are no longer referenced by any of the rows in the snapshots.query_stats table.  We need to delete these

— rows in small chunks, since deleting many GB in a single delete statement would cause lock escalation and

— an explosion in the size of the transaction log (individual query plans can be 10-50MB).

DECLARE @delete_batch_size BIGINT;

DECLARE @rows_affected INT;

SET @delete_batch_size = 500;

SET @rows_affected = 500;

WHILE ( @rows_affected = @delete_batch_size )

BEGIN

DELETE TOP (@delete_batch_size) snapshots.notable_query_plan

FROM snapshots.notable_query_plan AS qp

WHERE NOT EXISTS (SELECT snapshot_id

FROM snapshots.query_stats AS qs

WHERE qs.[sql_handle] = qp.[sql_handle]

AND qs.plan_handle = qp.plan_handle

AND qs.plan_generation_num =

qp.plan_generation_num

AND qs.statement_start_offset =

qp.statement_start_offset

AND qs.statement_end_offset =

qp.statement_end_offset

AND qs.creation_time = qp.creation_time);

SET @rows_affected = @@ROWCOUNT;

IF( @rows_affected > 0 )

BEGIN

RAISERROR (

‘Deleted %d orphaned rows from snapshots.notable_query_plan’,

0,

1,

@rows_affected) WITH NOWAIT;

END

— Check if the execution of the stored proc exceeded the @duration specified

IF ( @duration IS NOT NULL )

BEGIN

IF ( Getutcdate() >= @end_time )

BEGIN

PRINT ‘Stopping purge. More than ‘ +

CONVERT(NVARCHAR(MAX), @duration)

+

‘ minutes passed since the start of operation.’;

BREAK

END

END

— Check if somebody wanted to stop the purge operation

SELECT @stop_purge = COUNT(stop_purge)

FROM [core].[purge_info_internal]

IF ( @stop_purge > 0 )

BEGIN

PRINT ‘Stopping purge. Detected a user request to stop purge.’

;

BREAK

END

END;

— Do the same purge process for query text rows in the snapshots.notable_query_text table.

SET @rows_affected = 500;

WHILE ( @rows_affected = @delete_batch_size )

BEGIN

DELETE TOP (@delete_batch_size) snapshots.notable_query_text

FROM snapshots.notable_query_text AS qt

WHERE NOT EXISTS (SELECT snapshot_id

FROM snapshots.query_stats AS qs

WHERE qs.[sql_handle] = qt.[sql_handle]);

SET @rows_affected = @@ROWCOUNT;

IF( @rows_affected > 0 )

BEGIN

RAISERROR (

‘Deleted %d orphaned rows from snapshots.notable_query_text’,

0,

1,

@rows_affected) WITH NOWAIT;

END

— Check if the execution of the stored proc exceeded the @duration specified

IF ( @duration IS NOT NULL )

BEGIN

IF ( Getutcdate() >= @end_time )

BEGIN

PRINT ‘Stopping purge. More than ‘ +

CONVERT(NVARCHAR(MAX), @duration)

+

‘ minutes passed since the start of operation.’;

BREAK

END

END

— Check if somebody wanted to stop the purge operation

SELECT @stop_purge = COUNT(stop_purge)

FROM [core].[purge_info_internal]

IF ( @stop_purge > 0 )

BEGIN

PRINT ‘Stopping purge. Detected a user request to stop purge.’

;

BREAK

END

END;

END

 

Posted in Common | Leave a Comment »