You are on page 1of 21

Sys.databases and sys.

sysdatabases
Just wanted to write a short note on what is the difference between sys.Databases and
sys.sysDatabases. Well, both of them return some metadata related to databases hosted
on the instance. However, sys.Databases returns 56 columns and sys.sysDatabases
returns 12 columns. But why? whats the difference?
SQL Server 2005 introduced System Catalog Views, the preferred way of working with SQL
Server meta data. sys.Databases is a system catalog view and there are a number of such
views under the sys schema. sys.sysDatabases, howeever, are like the old meta data
tables that existed in SQL Server 2000 which is still there for backword compatibility
reasons. These are again views but return much less information compared to catalog
views (12 columns vs 56 columns). These are called as compatibility views.
Catalog views exist in every user database under the Views -> System Views node and
there a dozens of them allowing you to work with every type of metadata. They all exist
under sys schema and need to be addressed with the schema. SO if you run select * from
Databases (without prefixing sys schema), you will get an error. On the other hand,
sys.sysDatabases can be referred as sysDatabases (without prefixing any schema) or
dbo.sysDatabases. Simply becuase you might have a number of scripts referring to them in
that way written for SQL Server 2000 so nothing breaks.
It is preferred that you work with new system catalog views (not really new though) you
can observe that there is almost one column in sys.Databases for every database option

First question: If the IPALL TCP Dynmaic Ports setting is a specific number (say 1971) does
that signify that you have a static port of 1971 or a dynamic port that is currently 1971 and
may change at some point in the future.

Second question: This is the one I'm most curious about. We have an instance that has
had the same port (the value in the IPALL TCP Dynmaic Ports setting) for several years
through dozens of instance restarts. What actually causes the dynamic port to actually
change after an instance restart?
Dynamic Port Allocation
If you configure an instance of SQL Server to use dynamic port allocation, and you have not
yet restarted the instance of SQL Server, the registry values are set as follows:
TCPDynamicPorts = Blank
TCPPort = 0
However, if you configure an instance of SQL Server to use dynamic port allocation, and
you restart the instance of SQL Server, the registry values are set as follows:
TCPDynamicPorts = Current port that is used

TCPPort = Current port that is used


Static Port Allocation :
If you configure an instance of SQL Server to use a static port, and you have not yet
restarted the instance of SQL Server, the registry values are set as follows:
TCPDynamicPorts = Last port that is used
TCPPort = New static port to be used after the next restart; new static port that you set by
using the Server Network Utility
However, if you configure an instance of SQL Server to use a static port, and you restart the
instance of SQL Server, the registry values are set as follows:
TCPDynamicPorts = Blank
TCPPort = New static port that you set by using the Server Network Utility
for your second question Every time you start the named SQLServer, it uses the port that is allocated. In case if the
port is used by another program, then SQL Server chooses another port at the time of
restart i.e. The dynamic port is chosen at first startup, and will generally remain the
same through future restarts (stored in the Registry) - but if its used by another program
then SQL server will choose a new port. note: For Prod Servers, I use only static ports security and ease of manageability reasons.
Note: More cools thing to find out :
Check if Dynamic port is being used or not using T-SQL :
SELECT NAME
,protocol_desc
,type_desc
,state_desc
,is_admin_endpoint
,port
,is_dynamic_port
,ip_address
FROM sys.tcp_endpoints

Connection Problem
So let me give you step-by-step approach in troubleshooting connectivity issues with SQL Server.
Here is a flow of how connection to SQL Server is made:
1. Protocol used for making connections to SQL Server
Connecting is made using a protocol based on the "Client Protocols" order specified in your local box.

In the case of screenshot given above, the connection made to any SQL Server from this client machine will use
"Shared Memory" protocol first and if that connection fails, it will try to use "TCP/IP" protocol and if that fails,
connection request will be made using "Named Pipes" protocol. This is because I have all three protocols "Enabled"
and I have specified the order in this way.
Shared Memory protocol can be used only for local server connections whereby SQL Server should be running in the
same box where you are trying connect. This protocol will not help you to connect to a Clustered SQL Server instance
because the IP address of SQL Server is different from your local node.
You can also force to use specific protocol using syntax:
TCP:SQLSRVRNAME\INSTANCE for forcing connections to use TCP/IP protocol
NP:SQLSRVNAME\INSTANCE for forcing connections to use Named Pipe protocol instead you can also
use\\.\pipe\instancename\sql\query
LPC:SQLSRVNAME\INSTANCE for forcing connections to use Shared Memory protocol. LPC stands for Local
Procedure Call.
If you force these protocols, then connectivity will happen only using specific protocol and if that fails, connection will
fail without trying with further protocols. If you are connecting using a SQL Server alias created in the local client, then
the protocol specified in the alias will only be used.

2. Connecitivity flow when using TCP/IP Protocol


While making connections using TCP/IP protocol, the client driver will check whether the instance is DEFAULT
instance (MSSQLSERVER is the instance name for default instance) and if yes, the connection is made directly to
port 1433 using TCP protocol to the target SQL Server Instance.
For ex: If SQLMOSS is the instance name and if I connect from SQL Server Management Studio to SQLMOSS, a
connection request is sent to TCP port 1433 for the IP Address returned by DNS to the hostname SQLMOSS.
If this connection fails, a request is sent to port 1434 over UDP protocol and this is the port and protocol in which SQL
Server Browser will be listening for incoming requests in the target SQL Server instance SQLMOSS. Now SQL
Server Browser would have already read the port in which requested SQL Server Instance
SQLMOSS\MSSQLSERVER is listening from the registry. So SQL Server Browser knows the TCP port is say 1488, it
will return this information back to the requested client that SQLMOSS instance is listening on port 1488.
Now the client will reconnect to SQLMOSS instance using the TCP port 1488 and provided there is not firewall
blocking, this connection will succeed.
There are other things like authentication and authorization to complete a login successfully.
3. Authentication:
It means that the username and password you specified in the connection is valid. If you are using Windows
authentication and SQL Server server running with any of two mode "Mixed Mode" or "Windows-only" authentication,
SQL Server will request Local Security Authority Subsystem Service (LSASS) to verify the credentials of the specified
user. Again if the windows account is a local machine account, it is verified against local system security database
and if it is a domain account, LSASS then requests Active Directory to authenticate the user.
Once this user is authenticated, a token is then passed to SQL Server that authentication is successfull. There are
again two things in this authentication, they are NTLM or KERBEROS. KERBEROS needs SQL Server Service
Principal Name to be registered in Active Directory agains the SQL Server node name or the SQL Server Virtual
Server Name. If SPN's are not registered, then connection to failback to NTLM depending on your environment
settings. For more info about NTLM & Kerberos, refer this article
If the login is a SQL Server login, then SQL Server takes care of authenticating the user because SQL Server stores
the username and password. If target SQL Server instance is running in Windows-Only authentication mode then
though you are specifying correct password for the SQL login, the connection will fail because SQL Server will not
allow Non Windows login. You can change this to make SQL Server to allow Mixed Mode Authentication (Both SQL
logins and Windows logins) from SSMS -> Instance -> Properties -> Security -> Server Authentication. Please note
that you need to restart SQL Server if you make this change.
4. Authorization:
Once authentication succeeds, authorization phase starts whereby SQL Server checks the permission for accessing
the target database based on the TokenPerm cache built and if yes, the login succeeds and if not the connection will
fail with State 16.

Once authorization completes, you can submit your queries to execute in the SQL Server instance.
So by now, hope you have the complete flow of how connectivity happens from a client to SQL Server.
Here are some Troubleshooting tips:
1. To make sure SQL Server Browser is able to start (Port 1434 is available for SQL Server Browser to grab), you can
try start SQL Server Browser from command line :
C:\Program Files\Microsoft SQL Server\90\Shared>sqlbrowser.exe -c
You should see something like:
SQLBrowser: starting up in console mode
SQLBrowser: starting up SSRP redirection service
SQLBrowser is successfully listening on ::[1434]
SQLBrowser is successfully listening on 0.0.0.0[1434]
[9088]: Waiting for next request...
This step will ensure that SQL Browser works fine. If you are able to start SQL Server Browser from command line
and not as a service, check the service account configured for SQL Server Browser. To shutdown SQL Browser
started from command line, you have to press CTRL + C.
2. If SQL Server Browser failed to start, run TCPView from http://technet.microsoft.com/enus/sysinternals/bb897437 to make sure that no other process is already listening on 1434 UDP. For example if you
have SQL Server 2000 already installed on the same node where SQL Server Browser fails to come online, it could
be very well because SQL 2000 SSRP service already listening on 1434 and TCPView will help you to troubleshoot
this.
3. If connectivity to SQL Server instance fails, first thing to check is whether it is a Clustered SQL Server instance or a
Standalone.
If it is a clustered, try connecting from Active node of SQL Server to the SQL Server Instance. If this works then it
could be a firewall blocking connections from passive node and other clients.
To confirm that firewall is blocking the connectivity, use PortQry
fromhttp://www.microsoft.com/downloads/en/details.aspx?FamilyID=8355e537-1ea6-4569-aabbf248f4bd91d0&displaylang=en
Here is a sample output when I connect to a server name SQLMOSS (This should be a node name if it is a
standalone instance and virtual server name if it is clustered instance)

=============================================
Starting portqry.exe -n SQLMOSS -e 1434 -p UDP ...
Querying target system called: SQLMOSS
Attempting to resolve name to IP address...
Name resolved to 192.168.100.3
querying...
UDP port 1434 (ms-sql-m service): LISTENING or FILTERED
Sending SQL Server query to UDP port 1434...
Server's response:
ServerName SQLMOSS
InstanceName MSSQLSERVER
IsClustered No
Version 9.00.4035.00
tcp 1433
==== End of SQL Server query response ====
UDP port 1434 is LISTENING
portqry.exe -n SQLMOSS -e 1434 -p UDP exits with return code 0x00000000.
If you don't get any instance names returned in the result set, it should be firewall blocking the traffic. It will be a good
step to stop Firewall service and give it a try. If you are interested in adding Exception to firewall, add exception for

Port 1434-UDP for SQL Browser and Port xxxx-TCP for SQL Server. You can get the port in which SQL Server is
listening from SQL Server Errorlog.
If you don't have permission to install/download PortQry, try using telnet program available inbuilt in Windows (For
Win > 2008, you need to add Telnet Client Feature from Server Manager). If SQL Server is listening on port 1488
then when I run telnet SQLMOSS 1448 from command prompt, I got a blank screen like below which indicates that
SQL Server is listening to my request:

If this step fails, contact your system administrator with this data so that he can check the firewall logs.

SQL Server system is slow


1. run Performance monitor with the following counters:
Object Counter Instance
Processor % Processor Time _Total
PhysicalDisk Avg. Disk sec/Read _Total
PhysicalDisk Avg. Disk sec/Write main Log disk only
SQLServer:GeneralStatistics Logins/sec
SQLServer:SQL Statistics Batch Request/sec
SQLServer:SQL Statistics SQL Compilations/sec
SQLServer:SQL Statistics SQL Re-Compilations/sec
SQLServer:Latches Total Latch Wait Time (ms)
SQL Server:Locks Lock Wait Time (ms) _Total
Watch for peaks, note the height and duration of peaks
note the typical value away from peaks (not simply the average value displayed)
a. if % Processor Time is high,
sustained over 50%, peaks over 70%
then we need to look for CPU intensive queries
b. if disk read latency (Avg Disk sec/Read) is high,
> 0.020 sec (or 20ms) sustained, peaks over 0.040sec
then your disks are overloaded,
1st see if we can make the queries more efficient
2nd get more disks, spread data over as many physical disks as possible
c. of log disk write latency is high, >0.005
(it should read 0.001 or less)
then there is no option but to put the log on its own disks,
and configure it right
this cannot really be fixed with query or index tuning
unless you count reducing the SQL that write to the database
ie, turn off the transactions
d. if Logins/sec is sustained high,
>10 or even >1,
consider using connection pooling
e. if SQL Batch Requests/sec is very high,
> 1000/sec

be very careful about running profiler,


apply the CPU filter,
possibly only briefly w/o the CPU filter
DO NOT capture the stmt events
f. if Compiles are high,
>10,
use stored procedures for the high volume calls
g. if Recompiles are high,
> 2-5,
find the stored proc that are recompiling and fix it
there is a MS article on this, search: Lubor Kollar
h. suddend increase in Total latch wait time
could be blocking, investigate below,
2. run Profiler,
start a new trace
a. General
Template: "SQL ProfilerStandard"
Check the: "Save to file" option
NEVER Save to a table on the production server, NEVER EVER
b. Events:
keep just Stored Procedure->RPC:Completed" & "TQL->SQL:BatchCompleted"
c. DataColumns:
add DatabaseID , also add EndTime if you want to use Read80Trace
d. Filters:
set "CPU Greater than or equal" 10
learn to parse Profiler traces
search PSSDIAG, RML and Read80Trace on the MS site
PSSDIAG data collection utility,
the KB article is new, but the PSSDIAG download is old, feel free to bug MS for the
latest version, then share with us.
http://support.microsoft.com/kb/830232
Internal SQL Server Diagnostics Tools, Part 1: PSSDiag
http://msdn2.microsoft.com/en-us/library/aa175399(SQL.80).aspx
Description of the SQL Server Performance Analysis Utilities Read80Trace and
OSTRESS

http://support.microsoft.com/kb/887057
it is a good idea to learn how to use PSSDIAG anyways because if you need to open a
case with Microsoft PSS, they will ask you to use it to collect info.
Learn which items can be cleared to avoid overly large data collection
3. General information
exec xp_msver
GO
exec sp_configure
GO
provide the results of each
4a. Slowness not attributed to System CPU/disks or SQL queries
Was a SQL data/log file growth involved, I usually don't look for this
Check the SQL Server error logs, usually in the directory:
C rogram FilesMicrosoft SQL ServerMSSQLLog
Look at the ERRORLOG.X and SQLDumpXXXX.txt files
if there are indications of errors generated by the SQL Server engine itself, it is a good
idea to open a case with Microsoft PSS
4b. Mysterious slow down
-If your system runs well initially, but over time becomes horribly slow over time
-Intermitent severe slow downs that clear with no obvious reason
with a corresponding drop in the perf counter: Process->Sqlserv->Virtual Memory
-And the problem cannot be traced to CPU, disk or network, bad query plans, compiles
etc
-Queries with low CPU that normally run quickly, now run slow (but cpu is still low)
-Sysprocesses show many queries with wait time, but eventually going through
-The SQL logs show messages like:
reserve contiguous memory of Size=65536 or 131072 bytes failed
(this could be any power of 2, but failure to allocate 4-8MB is probably not a severe
problem
-A restart of SQL Server clears this problem or a while

SchemaBinding What & Why


August 6, 2014 by Kenneth Fisher

What
When you use the SchemaBinding keyword while creating
a view or function youbind the structure of any underlying tables or views. So what
does that mean? It means that as long as that schemabound object exists as a
schemabound object (ie you dont remove schemabinding) you are limited in changes
that can be made to the tables or views that it refers to.
That still sounds a bit confusing. This may be easier with an example (I like examples).

1
2

CREATE SCHEMA Bound


CREATE TABLE Table1 (Id Int, Col1 varchar(50), Col2 varchar(50))

CREATE TABLE Table2 (Id Int, Col1 varchar(50), Col2 varchar(50))

CREATE TABLE Table3 (Id Int, Col1 varchar(50), Col2 varchar(50))

CREATE VIEW UnBoundView AS

SELECT Id, Col1, Col2 FROM Bound.Table1

CREATE VIEW BoundView WITH SCHEMABINDING AS

SELECT Table2.Id, Table2.Col1, Table2.Col2

FROM Bound.Table2

10

JOIN Bound.Table3
ON Table2.Id = Table3.Id;

11
12

GO

So Ive created three tables and two views under the schema Bound. The first view is
unbound and references Table1 and the second view references tables Table2 and
Table3 and is schemabound. I do want to point out a couple of things.

Because I created all the objects under the CREATE statement for the schema
they are all contained within that schema.

When creating a schemabound view or function you have to use the two part
name (include the schema name) for any tables or views you reference within it.

Next Im going to try to drop a column referenced by each of the views.

ALTER TABLE Bound.Table1 DROP COLUMN Col2;

GO

This one works fine. Bound.Table1.Col2 is not referenced by any schemabound objects.

ALTER TABLE Bound.Table2 DROP COLUMN Col2;

GO

This one gets an error.

Msg 5074, Level 16, State 1, Line 1


The object BoundView is dependent on column Col2.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Col2 failed because one or more
objects access this column.
One of my favorite parts of writing a blog is when I learn something new. In this case I
had made the incorrect assumption that if a table was referenced by a schemabound
function or view that you could not make any changes to its structure. Turns out that
only the columns referenced by the function or view are bound.
So for example these work:

ALTER TABLE Bound.Table3 ALTER COLUMN Col1 varchar(51);

ALTER TABLE Bound.Table2 ADD Col3 varchar(50);

ALTER TABLE Bound.Table2 DROP COLUMN Col3;

ALTER TABLE Bound.Table2 ALTER COLUMN Col3 varchar(51);

ALTER TABLE Bound.Table2 ADD CONSTRAINT df_Tb2_Col1 DEFAULT 'A' FOR Col1

And these dont:

ALTER TABLE Bound.Table2 ALTER COLUMN Col1 varchar(51);

ALTER TABLE Bound.Table2 DROP COLUMN Col2;

And here are a couple of other restrictions & factoids.

You can not change the collation of a database with schemabound objects.

You can not use SELECT * in a schemabound view.

You can not run sp_refreshview on a schemabound view. You do get a rather
unhelpful error though.

You can make any change to the table that do not affect the structure of the
bound columns.

You can find out if an object is schemabound by looking at the column


is_schema_bound in sys.sql_modules or the system function
OBJECTPROPERTY(object_id, is_schema_bound).

If you reference a view or function in a schemabound view or function then that


view or function must also be schemabound.

Objects that are bound (tables/views) can not be dropped while a schemabound
object references them

Why
Schemabinding isnt a commonly used tool unless you are setting up an indexed
view and then it can get lost in the crowd of other required restrictions. It does have
uses outside of indexed views however. I could see using it if there is a mission critical
view/function that just CANT break. By including the SCHEMABINDING clause you
protect the view/function from unexpected changes to the tables underneath them. In
fact if all of the data access in an application is through views and TVFs I might consider
schemabinding all of them. It might be less important in a small shop with only a

couple of developers and/or DBAs where everyone knows what changes are being made
and what effect they will have. However if you are in a big shop with dozens of
applications, may of which use the same databases, you can easily make a change to a
table that breaks code in another application that you were completely unaware of.
So in the end SCHEMABINDING isnt a world changing clause but still one that you
should be aware of.

Difference between Stored procedure and function?


1.
Function has a return type but Stored procedure doesn't have a return type.
2.
Stored Procedure supports IN/OUT/IN-OUT Parameters while function supports only IN
parameters.
3.
Stored procedure can contain all the DML(Select,update,insert,delete) statements but
function can contain only select statement.
4.
Function can be called from a stored procedure but stored procedure cannot be executed
from a function.
5.
For Exception Handling, the stored procedure can contain try---catch block but Function
doesn't support try---catch block.
6.
Function can be called in a SELECT statement not a stored procedure.
What is the purpose of an Index?
An index is used when we need a bookmark for our table. They are just used to speed up
searches/queries. A table can only have one Clustered index and up to 249 Non-Clustered
Indexes.
Clustered Index:
A clustered index physically sorts the data in a table.The value of a clustered index is a key-value
pair,where key is the index key and value is the actual value.
If you create a primary key in a table,a clustered index is created by default.
Non- Clustered Index:
A non-clustered index sorts the data logically but not physically.The value of a non-clustered
index is not the data but a pointer to the data page.So, we can say a non-clustered index is
dependent on the clustered index.In the absence of clustered index, it refers a physical location in
the Heap for value.

You might also like