Copyright © 2008-2015 Paula DiTallo

Tag Cloud

How do I set a trace in SQL Server?

Think of this as a lightweight alternative to SQL profiler. Under the hood of SQL profiler, there exists SQL Trace  -- which provides a collection of stored procedures to generate trace info. Cut and paste the t-script below to see how it works.

-- Pay attention to what the server settings for traces look like first:

select * from sys.traces


-- you are looking to make sure there isn't already a trace file set somewhere
-- In any case you will need to create a new trace, make sure the @tracefile doesn't exist on the disk yet

declare @myTracefile nvarchar(500) set @tracefile=N'c:\temp\myTraceFile.trc'

declare @myTrace_id int

declare @maxsize bigint

set @maxsize =1

exec sp_trace_create @myTrace_id output,2,@MyTracefile ,@maxsize



---  add the result columns you care about

--  if you don't have any other traces set, you'll be set to 1, if not, run the select * sys.traces again to see
-- what got assigned. look up in sys.traces to find the @mytrace_id,
--  in this example, I will assume its 1 for now so that is why you see: @mytrace_id=1

declare @myTrace_id int

set @myTrace_id=1

declare @xon bit

set @xon=1

declare @current int

set @current =1

while(@current  <10)   -- 10 times is just an arbitrary number of times i might log something
                                               -- pick whatever you want

      -- here is where you figure out what events you want to log to the file.  
      -- Go here to decide:

      -- Try it out for now, using #14 -- that's probably not what you want, but get it to work first.

      exec sp_trace_setevent @myTrace_id,14, @current,@xon

      set @current=@current+1

-- later you'll want to look at it

declare @myTrace_id int

set @myTrace_id=1

exec sp_trace_setstatus  @myTrace_id,1

-- see the traced event

select yourlogin, dbinstancename,* from ::fn_trace_gettable(N'myTraceFile.trc',default)


-- Once you're done, you'll need to cleanup
-- stop the trace and delete the file

declare @myTrace_id int

set @myTrace_id=1

exec sp_trace_setstatus @myTrace_id,0

exec sp_trace_setstatus @myTrace_id,2  -- delete def from server


DB2: How do I get the Column Definitions, Column Descriptions?

These general statements will get you the information that you're looking for:


 AND TABLE_NAME = 'YourTableName'

This will get you the definitions of the columns:

t.table_schema as Library
,c.character_maximum_length as Length
,c.numeric_precision as Precision
,c.numeric_scale as Scale
FROM sysibm.tables t
JOIN sysibm.columns c
   on t.table_schema = c.table_schema
  and t.table_name = c.table_name
WHERE t.table_schema = 'YourSchema'
and t.table_name = 'YourTableName'
order by t.table_name, c.ordinal_position

sql server: How can I list or review the last restores for all the databases on a server?

Go to the server your are interested in gathering the information from, then issue this statement:

WITH LastRestoresOnServer AS
    sysdb.[name] as dbName,
   ROW_NUMBER() OVER (PARTITION BY sysDb.Name ORDER BY r.[restore_date] DESC) as RN
FROM master.sys.databases sysdb
LEFT OUTER JOIN msdb.dbo.[restorehistory] r ON r.[destination_database_name] = sysDb.Name
FROM [LastRestoresOnServer]

How do I Fix "Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CS_AS" and "SQL_Latin1_General_CP1_CI_AS"

You were probably trying to do a comparison between 2 databases with different collation settings on a WHERE clause or on a  join. Here's how you would do the comparison with a JOIN:

Select * 
from source db1.schema.table1 as t1
join source db2.schema.table2 as t2
on t1.col1
collate SQL_Latin1_General_CP1_CS_AS = t2.col1 COLLATE SQL_Latin1_General_CP1_CS_AS

mssql2008+ : How do I manage transactions in stored procedures?

This pattern works well:

USE [yourDatabase]


  @PersonId INT,
  @NewMoneyCollected MONEY = 0
      UPDATE OrganizationTripFunding
      SET Balance = MoneyCollectedAllYear + @NewMoneyCollected
      WHERE PersonId = @PersonID;
    IF @@TRANCOUNT > 0

    DECLARE @ErrorNumber INT = ERROR_NUMBER();
    DECLARE @ErrorLine INT = ERROR_LINE();
    DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
    DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
    DECLARE @ErrorState INT = ERROR_STATE();
-- use as debugging tool -- PRINT 'error number: ' + CAST(@ErrorNumber AS VARCHAR(10)); -- PRINT 'line number: ' + CAST(@ErrorLine AS VARCHAR(10)); RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState); END CATCH END; GO

SSIS 2012: My Deployment fails with the message "query the operation_messages view"

The full error message reads as "Failed to deploy project. For more information, query the operation_messages view for the operation identifier '39212'. (Microsoft SQL Server, Error: 27203)

In a nutshell, the most common reason for this is the latency between SQL Server logging the deployment operation within the SSIS catalog database and the stored procs that actually commit the deployment.

Try the deployment again.

How Do I Install an Eclipse Plugin from a *.zip File?

If you aren't able to install from the Help\Install New Software menu, it is probably because the zip file doesn't have the content.jar/artifacts.jar needed to do so. You will need to navigate to where you've installed Eclipse, then follow these steps:
1.  Navigate to the Dropin drectory
2. Create a new subdirectory (folder).
3. Expand the zip file to the subdirectory folder.
4. Restart Eclipse
5.  Under the Windows\Open Perspective menu, look for your plugin.

Sql Server: Orphaned user name; Can't login, User name disappeared from my database

This usually happens when you restore a database. For example, you restore a copy of production database X to your QA server. In essence, you have overwritten the user info of that specific database with what exists in production. This creates an orphan user -- where you have no login associated with a user in that database on a server that once associated that user with the old copy of the database.

Here is what to do fix the issue:

1.  Validate that what you think is the problem is the  problem. Do this by listing the known orphans. You may have others show up--but be sure the id you are interested in is on the list:

use [your database instance]


EXEC sp_change_users_login 'Report'

2. Fix the broken login:

EXEC sp_change_users_login 'Auto_Fix', 'orphan username'

SQL Server: Restoring a backup generates this error: Operating system error 5(Access is denied.).

There are several reasons for this. The most common reason is that the account you are using while logged into mssql through ssms does not have access to the drive definition you are using as your source. Network drives are a good example of an access conflict.

Assuming you have access to the drive, try redirecting the network drive to a local drive letter via xp_cmdshell  (Note: be sure use of xp_cmdshell is enabled) .

exec master..xp_cmdshell 'net use Z: "\\BackupServerXX\<share>\PathWithoutTrailingSlash" YourADpasswordHere /user:domain\your.Username'
Declare @restorefile varchar(1024) = 'Z:\thebackupfile.bak'
Restore database x
From disk = @restoreFile

When you are done, or if you've made a mistake and need to reassign the drive, delete the reference.

exec master..xp_cmdshell 'net use Z: /delete'

SQL Server: How do I generate the table schema and populate it with inserts in a script?

In SSMS, there's a Generate Script utility (read:  only available under version 2008 and up) .

Here are the steps you would need to take to make use of the utility:

  1. Right click on the database you're interested in and go to Tasks -> Generate Scripts
  2. Select the tables and/or any other objects you'd like in order to get them into the script.
  3. Navigate to Set scripting options. Click on Advanced.
  4. Under the General category, navigate to Type of data to script
  5. Select the Schema and Data option to get the insert statements generated. Click OK.

How do I find the largest files on my disk (storage)?

Here's an example using forfiles to scan your storage. This command line will look for files over 200mb on the C:\ drive after 1/1/2014.

forfiles /P C:\ /M *.* /S /D +"01/01/2014"  /C "cmd /c if @fsize gtr 209715200 echo @path @fsize @fdate @ftime"

For more information, check out Microsoft's examples and syntax page:

Sql Server: Select Count(*) throws the error: Arithmetic overflow error converting expression to data type int

Try using count_big(*) instead-- this is defined as bigint instead of int.

In this example, I am looking for how many 100s of millions of rows exist by product type where each row is roughly 300 bytes wide to ultimately obtain how many gigabytes of data I need to provision.

select x.ProductType,
       count_big(*) as ProdCount,
      (count_big(*)*300) as TotalBytes,
      ((count_big(*)*300)/1073741824) as Gigabytes
 from fdwintegration.etl.fuelpriceindex x
  inner join fdwintegration.etl.FuelProducts y
   on x.ProductIndicator = y.ProductIndicator
    and x.ProductType = y.ProductType
   where x.ProductIndicator = 'D'
   group by x.ProductType
order by x.ProductType

How Do I Alphabetize the Application Icons on my Droid?

Click on the App Button (aka: "Drawer" ) -- That's the key with the multiple squares, click on menu , select view type, select alphabetical grid.

Windows: How do I find what process is locking a file?

Open up an MSDOS command window. Type :

net file

The id, path, user name, loc# for the file will show up in a text list. Once you find the file you want unlock, you'll need to remember the id. To unlock the file, go back to the MSDOS command window. Type:

net file 99/close    (where 99 = file id)

On a windows server there are 2 other ways:
1. From an MSDOS command window type: Openfiles.exe /query /s YOUR_SERVER_NAME
2. Server Manager>Roles>File Services> Share and Storage Management (right click on SaSM) >Manage Open File

Linux/Unix: How do I find any partial file name on any directory?

We've all been there-- like -- where's that offline htm file i bothered to save last week ... oh I think it was blue something... or was it something blue?

find ../ -name '*blue*.htm*'  -print

If you want to keep it in an output file to sort through later while you do something else:

find ../ -name '*blue*.htm*'  -print > $HOME/ foundBlue.txt


My old (generation 2) nano iPOD won't shut off.

Try holding down the Menu and Selector (push-button circle in the center) down at the same time for at least 2 seconds.

My iPOD keeps saying "Do Not Disconnect" while charging. I can't listen to anything.

The simplest answer is because the iPOD software detects that it is unsafe (read: data loss) for your iPOD, Computer or both if you were to disconnect the cable without ejecting the device first.

Here's what to do:

On the Mac--

  1. Click on the Finder icon
  2. Pick the iPOD icon.
  3. Navigate to the File menu--select Eject iPOD

On a Windows OpSys device--

  1. On the Start menu, click Computer (e.g. Windows 7).
  2. Right-click on the drive/device letter or iPOD icon (read: the icon doesn't always appear)
  3. Select Eject.

The message should go away while you're still plugged in. You should be able to charge and listen at the same time! :)

How do I save frequently used SQL Statements in SQL Server?

One convenient way is to make use of the template feature (aka: Template Explorere) in SSMS.

1. Navigate to the View menu in SSMS
2. Select Template Explorer->right click on SQL Server Tempaltes.
3. Click New and create folder; use to add/edit templates.

How do I switch montor postions? Switching cables didn't help.

For Windows 7:
1. Right click any blank area on your desktop. 
2. Left click Personalize->Display Settings. A  window will open that shows a monitor.
3. Navigate to Change Display Settings. A new window will appear showing 2 monitors. 
4. Click Identify Monitors.  When the monitor you are on is the main monitor, you will see "This is currently your main display" under Multiple displays. To change this, click on the other monitor and check the box that says "Make this my main display". Click Apply.
5. If  you want to change how the mouse drags from right to left/left to right,  click and drag the right hand monitor left to the left of the original left monitor and release the drag.  That will change the positions of the monitors so that the mouse motion will be the way you want them.

Which DMVs are most helpful? Is there a list of them?

As with most questions asked about monitoring/assessing/administering MS SQL Server installations, the answer is "it depends".

There are many other blogs/resources/etc. online that can get into the specifics--think of this mini-blog as a snake-bit kit! :) Overall, to get to a list of objects that fall under the DMV (Dynamic Management Views) category, type this:

-- This will show you the views and the functions of all dmv objects
SELECT name, type, type_desc
FROM sys.system_objects
 WHERE name LIKE 'dm_%'
-- and type = 'V'
  ORDER BY name

Here are a few useful DMVs to get started with...

-- Query Plans
-- stats about cached query plans
select * from sys.dm_exec_query_stats

-- identifies query plans that are cached
select * from sys.dm_exec_cached_plans

-- I/O
select * from sys.dm_io_pending_io_requests
select * from sys.dm_io_virtual_file_stats(null,null)  -- //
stats for all data and log files

-- Reqs/Executions

-- lists active user/internal task connects
select * from sys.dm_exec_sessions

-- established connects
select * from sys.dm_exec_connections

-- lists info about all reqs executing
select * from sys.dm_exec_requests

How can I tell when a stored proc (or function) in sql server was last modified?

You're really looking of the modify_date in the sys.objects table where the type is either a stored proc or a function. This works on a database by database level -- to elevate this search to the server level, you'll have to use the loop sproc sp_msforeachdb

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'  -- change 'P' to 'FN' if you're looking for a function 
 and modify_date between cast('2013-09-10' as date) and cast('2013-09-20' as date) 

How do I change the value of a column in a CASE statement and eliminate NULLs?

In t-sql/mssql, if you have a known NULL value  you can issue a statement like:

  ISNULL(BirthDate,'1/1/1970 12:00:00 AM') as BirthDate
FROM Drviers

The ISNULL function is replacing any nulls found in the BirthDate column to a default value of 1/1/1970.

In other situations, you may not have just NULL values, but other possibilities as well. 

 ISNULL(BirthDate,'1/1/1970 12:00:00 AM') as BirthDate,
   WHEN BusinessPhone IS NULL OR BusinessPhone = ''
        THEN 'Unknown'
   ELSE BusinessPhone
 END as BusinessPhone
FROM Drviers

The case statement is evaluating the value found for the BusinessPhone column. If the value is NULL or set to '', then the default value is Unknown, else if the value isn't null or set to '', then retain the value for the  BusinessPhone column found.

I get the error "Can't connect to SSISServer" . How do I fix this?

If you're seeing this error, or a similar access denied error you'll need to have your windows account given DCOM permissions. DBAs generally have the ability to add you.

If you're a DBA and want to add a developer to be able to connect to the SSIS services to deploy packages here's a quick punch list:

  1. Logon to the target SQL Server. Go to Start->Run  type lusrmgr.msc
  2. In the Local Users and Groups dialog box, click Groups->Ditributed COM users
  3. Once in the Distributed COM users properties dialog box, click Add
  4. Select the User click OK
  5. Go back to Start->Run type dcomcnfg
  6. In the Component Services dialog box, drill down to Component Services->Computers->MyComputer
  7. Under DCOM Config, right click MsDtsServer, click Properties
  8. In MsDtsServer100 Properties dialog box, click Security tab
  9. Under Launch and Activate Permissions, go to Customize->Edit
  10. Under Launch Permissions click Add
  11. Under Select Users or Groups, type the user name, click OK
  12. Under Permissions for the user, Allow or check the checkbox for all 4 (local,remote launch/activation)
  13. Click OK. Do steps 11-12 for Access Permissions.

How do I do a SELECT TOP in SQL for DB2 on an iSeries (Power7) ?

This answer depends on what version of SQL you're running. A FETCH clause will work for all. Here's an example:


The equivalent in T-SQL would be:


SQL Server Management Studio: Why do I get "Saving changes is not permitted" ?

This happens when you're in the SSMS gui making changes to the table that either affect the behavior of an index, cause existing data to be truncated/nulled, etc. This can also happen you try to change the order of columns, or change datatypes. 

If your credentials allow it, you can get past this message in order to truly shoot yourself in the foot! :)

  • Navigate to Tools --> Options
  • Expand Desingers
  • Click on  Table and Database Designers
  • Check the box Prevent Saving changes that require table to be re-created.