Boilerplate TSQL Transaction Code for SQL Server 2005

This is some useful stuff from 4guysfromrolla.com

BEGIN TRY
   BEGIN TRANSACTION    -- Start the transaction

   -- Your code here
-- If we reach here, success! COMMIT END TRY BEGIN CATCH -- Whoops, there was an error IF @@TRANCOUNT > 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH

SQL Server Reporting Services Email Subscriptions Not Going Out

We recently ran into a problem with SSRS where our email subscriptions were processing, but no emails were going out.

SSRS doesn’t really give you any info in the web interface to give you any clue that something isn’t work right, let alone help you figure out what the problem is.

I was able to solve the problem by looking at the various log files that SSRS creates:  ReportServerWebApp__X, ReportServerService__X, and ReportServer__X.

In these config files I was able to find some errors coming back from our mail server. 

This lead me to discover that the problem was with how the email addresses were formatted. 

The issue was that we recently changed which mail server we used for sending out these emails, and we have moved from an Exchange 2003 server to an Exchange 2007 server.

Exchange 2003 would accept domain accounts as destinations for emails, so you could send an email to “cmay” and it would be delivered.  It seems that Exchange 2007 requires that you provide the full email address: cmay@company.com

After changing some of the SPs that served up the data, all worked once again.

 

How To Strip Off the Time From DateTime (or Just Get The Date Portion)

Every now and then I go to my blog to lookup something I wrote before only to find that I never posted it.

I would have bet someone $20 that I had posted something on how to strip off the time from a DateTime in SQL.  Why would you do this?

Well, lets say that have some autogenerated DateTime field (CreatedOn?) that you later want to join with another field, but the other field only knows the DATE when something happened, not the exact Date and Time.

So, you can use the following code to just get the DATE and zero out the time component:

SELECT CAST( CONVERT( CHAR(8), GetDate(), 112) AS DATETIME)

SQL "NOT IN" Will Fail If The List Contains A Null

If you are using the NOT IN clause with a SQL Select statement with SQL Server it will not work if there is a null value in the list.  Say for example you want to do:

SELECT * FROM
Employees
Where
Employee.Id NOT IN
(
   Select EmployeeId from
   Salaries
   where Salary < 100000
)

If the inner select returns a null value then the outer select statement will return no rows.

To try it, just run these 2 SQL statments against any table in your DB.

-- will return rows
SELECT * FROM
sometable
WHERE ID NOT IN (1,2,3)

-- will return nothing
SELECT * FROM
sometable
WHERE ID NOT IN (1,2,3, null)

Dealing with null data in SSRS

When working with a SSRS report, the report framework will already “Denull” everything.  But in some cases, for example when you are working with numbers, you might want to display a value in lue of the “” that is displayed for nulls.

Now you would THINK, that they would just use the same ISNULL syntax that everyone knows from sql programming.

HAHAHHAHA… of course they didn’t do that.

Instead you have to use a combo of IIF and IsNothing like so:

=IIF(IsNothing(Fields!Quantity.Value),0,Fields!Quantity.Value)

It isn’t THAT big of a pain, but I wish MS would sometimes just realize how much easier it would be for them to just create an IsNull function in their own codebase than make their users write this out.

Oh well.  I guess when it comes to problems with SSRS, this is waaaaaaayyyyy down my list.

Speaking of “my problems with SSRS”… when are you guys going to support TBLR text??  Drives me nuts.  Everyone does “vertical text” in TBLR format, for pretty much every application, but now in SSRS you are forced to use TBRL.  When you give these reports to engineers that is the very first thing they say “You need to turn this text around the other way”…. yes I know, I got my degree in Civil Engineering with a focus on structure design, so when you come from a background of seeing all vertical text (like on any plans) as ALWAYS, by requirement, aligned in a TBLR manner, and then you are forced to cock your head the other way to read it, it is really a pain.

But I guess I would still like to see MS fix their *terrible* PDF rendering first.  I just LOVE watching my reports take 4x as long as in CR, and end up 100x bigger in file size than they are after being saved in acrobat (15 MB for a 1 page PDF, open in Acrobat, save the file again, down to 150KB, with no visible change in appearance or quality).

 

Moving changes from one table to another

You just screwed up the database, and now you need to make some surgical repairs to the database.

Or maybe you have data in development and production tables and you want to move some data changes from one to the other.

Basically the problem is that you have 2 tables with the same schema where 1 column has some different values in one table when compared with the other.

You can’t do an update on an inner join statement, but you can create an updatable view containing the fields you need and then run an update statement on it.

A view is updatable if it meets the following conditions:

A view is updatable if:

  • select_statement has no aggregate functions in the select list and does not contain the TOP, GROUP BY, UNION, or DISTINCT clauses. Aggregate functions can be used in a in a subquery in the FROM clause as long as the values returned by the functions are not modified. For more information, see Aggregate Functions.
  • select_statement has no derived columns in the select list. Derived columns are result set columns formed by anything other than a simple column expression, such as using functions or addition or subtraction operators.
  • The FROM clause in the select_statement references at least one table. select_statement must have more than nontabular expressions, which are expressions that are not derived from a table. For example, this view is not updatable:
CREATE VIEW NoTable AS
 SELECT GETDATE() AS CurrentDate,
 @@LANGUAGE AS CurrentLanguage,
 CURRENT_USER AS CurrentUser

Getting Just the Date Out Of GETDATE

SQL Servers’ GETDATE() function will return the current DateTime.  But what if you just want the current date.

CAST(FLOOR(CAST(GETDATE() AS float)) AS datetime)

or

CAST(CONVERT(VARCHAR(10), GETDATE(), 111) AS DATETIME)

See this page for even more options.

Or, if you want to get just the current time out of GETDATE or any datetime for that matter, check out this page (it is one of the FAQs).

 

Problems with SQL RS on Windows 2000

I was having problems with getting RS to work correctly on a windows 2000 server.  I would browse to the page, and it would prompt me for my credentials.  I would use the Admin loign, and it wouldn’t take, finally giving me an error like this:

Server Error in ‘/Reports’ Application.
——————————————————————————–

Access to the path “C:Program FilesMicrosoft SQL ServerMSSQLReporting ServicesReportManagerbin” is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path “C:Program FilesMicrosoft SQL ServerMSSQLReporting ServicesReportManagerbin” is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate=”true”/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

I found someone who figured out the impersonation problem:

The problem happens when installing RS on Windows 2000 Server that is a domain controller.  RS doesn’t do the setup correctly.  The basic steps to fix the problem are

1. Grant impersonate privilege to IWAM_<machine> account (see knowledge base article 824308).  Go to domain controller security policy  in administrative tools. Click security settings -> Click local policies -> click user right assignment.  In the right pane, double click impersonate a client after authentication.  In security policy setting window, click define these policy settings.  Click add -> click browse.  In select users or groups window, select IWAM account name and click add.  Then, click Ok -> Click OK -> Click OK.  At command prompt, type the following command: secedit /refreshpolicy machine_policy /enforce.  Then, type iisreset.

2.  Remove IWAM_<machine> account from guest group.  Go to active directory users and computers in administrative tools.  Open users folder.  In right pane, double click IWAM_<machine>.  Select member of tab.  Remove guest.  Click OK.

3.  Reboot.

4.  Run rsactivate.  From command prompt, change directory to C:Program FilesMicrosoft SQL Server80ToolsBinn.  The run following command: RSActivate.exe -c “c:Program FilesMicrosoft SQL ServerMSSQLReporting ServicesReportServerRSReportServer.config” -t.

See the following link for more details http://msdn.microsoft.com/library/default.asp?url=/library/en-us/RSINSTALL/htm/gs_installingrs_v1_8k82.asp .

For now, this seems to have fixed this problem.