Tuesday, November 12, 2013

Setting CMD as the default

So I've tried setting CMD as the default program to run .cmd files in Windows 8.

Click Windows button, and then search for default and then choose Default Programs.

Inside of Default Programs, it is not possible to associate .cmd files with CMD. Isn't that maddening?

If I find a way to do this, then I'll set it up so .cmd files on my system run with Adminstrator authority. 

The idea is:
1. I'm developing on the machine, and need to change / manage / mangle various files and settings quickly through .cmd files.
2. I don't want to be prompted UAC every time I do (1), above.

So I'm thinking it's a default "security feature" that you can't rewire the association without a registry hack, but that's going to be my next step.

Tuesday, November 5, 2013

Windows Server 2012 and SQL 2012 Configuration Manager

From the techNet article:

To access SQL Server Configuration Manager Using Windows 8

Because SQL Server Configuration Manager is a snap-in for the Microsoft Management Console program and not a stand-alone program, SQL Server Configuration Manager not does not appear as an application when running Windows 8. To open SQL Server Configuration Manager, in the Search charm, under Apps, type SQLServerManager11.msc 


But then, once you've found it, push enter to start it.

Then, go back, and search again. This time, it will show up on the left hand side of the search window, as a previously run app. Right click it, and choose "Pin To Start" so you don't have to hunt for the msc the next time.

Alternate Method


If you're more the "make my own" type, then you can :

Get to desktop mode in Windows 8.
Right click on the desktop.
Choose New >> Shortcut
As the location of the item, paste  SQLServerManager11.msc
Click OK.
Right click your new shortcut, and from the pop up menu, choose "Pin To Start".

Tuesday, October 22, 2013

How To Add Yourself To SQL

The other day, I locked myself out of my SQL Server by joining the VM to a domain. When I joined the domain, only the local users had access, because I hadn’t added the domain admins to the machine as sysadmin role members yet, since the machine wasn’t yet part of the domain.

It's a circle!

Anyway, I found myself unable to login to my SQL 2012 instance using Windows Authentication. While adding myself back, I discovered that sp_addsrvrolemember has been deprecated.
net stop <<servicename>>
net start MSSQLSERVER /m
sqlcmd –E –S.
Then, in SQL Server 2008 R2 and earlier, I would do this:

create login [DOMAIN\LOGIN] from windows;
go
exec sp_addsrvrolemember [ @loginame= ] 'domain\login' , [ @rolename = ] 'role';
go
But now, in SQL 2012, to be future proof, I have to upgrade my script to look like this:
create login [DOMAIN\LOGIN] from windows;
go
alter server role 'role' add member='domain\login';
go
One MS reference:
sp_addsrvrolemember (Transact-SQL)

Tuesday, October 15, 2013

Changing A SQL Server Name

Changing the name of my SQL Server has been anything BUT pretty, easy, or straightforward. I want to collect the various pieces of the process here, so I can remember them when I need them again.

To change the name in the O/S:

** If joining a domain, do it all at once, if at ALL possible **


To then change the name of the already installed SQL Instance:



select @@servername -- was 
go
sp_helpserver -- was 
go
select serverproperty('servername') -- was 
go
select * from sys.servers; -- was 
go

sp_dropserver '';
GO
sp_addserver '', local;
GO

select @@servername -- is now 
go
sp_helpserver -- is now 
go
select serverproperty('servername') -- was already 
go
select * from sys.servers; -- is now 
go



Tuesday, October 8, 2013

In another time, and another place . . .

Being an engineer really is like being an artisan class. 

If we were in ancient Greece, though, would that make us landowners?

Since we're not, are there any lessons we can learn from Sparta? Two things spring to mind, from recent life lessons:

1. Focus
The classes were separated by function. Say what you will about classes, there still would have been great shoemakers, good shoemakers, and just-ok shoemakers within the trade class. The goal, I think, of every engineer, is to be the best within their class or specialty. Which brings me to . . .

2. Specialize
The idea of being both a shoemaker and a then a sandal repair specialist might seem silly to us (I mean, really. Beach sandals are like a $1) but if you needed your sandals repaired TODAY so you could march to war tomorrow, would you go to the just-ok maker, for the just-ok price? Or would you pay the higher price for the greater speed and quality of the specialist across town?

I have, and continue, to drive across town for quality. Do you?


Tuesday, October 1, 2013

Interviewee Questions To Ask

Other than a note on “when do I get paid?” there is nothing HR-ish in the following document about pay, salary, pay ranges, or even expected compensation, bonus plan, etc. etc. etc.

I’m not worried about that when hiring for a DBA, SQL Developer, SSIS Developer, etc. role.

Instead, if I’m hiring in to a place filled with poisonous man eating sociopaths, I want to know it up front so I can avoid it all together. I’ve already worked at one of those, and my therapist says I’m making remarkable progress, ha ha ho ho.

Instead, this list is designed to provide the job seeking candidate a fighting chance to not forget the really important things BEFORE they make the jump to a new customer, client, or employer.

I originally designed this as a tool for my own passive job hunt years ago, and have kept it up to date over time. This list is specific to the questions I ask about an environment going in.

Specifically, I want to ask about a few main areas:
  • Hours & Working Conditions
    • Hours
    • Documentation & CCB/CR
    • Client(s) & Customer Service
  • Position & Corporate
    • Positional
    • Corporate
    • Equipment
  • SQL
    • SQL Server Itself
    • DB’s
  • Hardware
    • Location, Location, Location
    • Physical & Virtual
    • Storage
    • Outage & Troubleshooting
    • Getting Work Done

I also watch the interviewers response when I still have twenty questions left – I’ll tell them I do, and watch their reaction. If they aren’t prepared to answer my questions during my one chance to meet and talk with them before we do business, that can also be rather instructive.

Oh, and kids? Turn off your cell phone.

Download the Interview Questions

Tuesday, September 24, 2013

Blog Code Formatting

http://danielthat.blogspot.com/2013/03/how-to-display-code-in-blogger-posts.html
 
I've started using the code outlines marked in the above article. He references a style chart with a bunch of styles. Here's what my inserted header block looks like, for Linux, C#, and SQL code snippets.
 





Here's the list of brushes currently :
http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/

Basically, it all comes down to the idea that you put your code into a <pre> block, with an attribute of the brush type you want. Like this:

Tuesday, September 17, 2013

Ubuntu 13.04 RDP


Connect to Ubuntu 13.04 from Windows via RDP Protocol using Windows 8 .

After some research, here's the command line version:


sudo apt-get install xrdp

sudo apt-get install gnome-session-fallback

echo “gnome-session –session=gnome-fallback” > ~/.xsession

sudo /etc/init.d/xrdp restart



Tuesday, September 10, 2013

TFS error TF30172

So I'm getting error TF30172 when I'm connecting to a team project on my TFS server. This is annoying, because I had created the existing team projects a different way, and now I'm trying to add them from Visual Studio 2010.
Here's the error I'm getting:
TF30172_ErrorMsg
I found this comment online by Buck Hodges
Unfortunately, there is no fix or change that will ever make it such that VS 2010 will be able to create a team project on a TFS 2012 server. The compat patch that you are referencing addresses a lot of things to make working with TFS 2012 from VS 2010 work well, but creating a team project is not one. You will have to use VS 2012 (or the standalone Team Explorer 2012) to create a team project.
Here's the KB article about a related patch:
http://support.microsoft.com/kb/2662296?wa=wsignin1.0
I first thought about installing this:
Visual Studio 2010 SP1 Team Foundation Server 2012 Compatibility GDR
http://www.microsoft.com/en-us/download/confirmation.aspx?id=29082
And then I thought - maybe this?
Team Explorer for Microsoft Visual Studio 2012
http://www.microsoft.com/en-us/download/confirmation.aspx?id=30656
But ultimately? I settled for a two-part system. I manage my team projects through VS 2012's installed tools, and develop using VS 2010; this lets me do all my check ins and outs there.












Tuesday, September 3, 2013

Not-Quite-Open-Source Project Management

While trying to solve the "get this calendar online" problem I've been facing recently, I've also run across a number of other, generally online-only products available.

Here they are, in no particular order:

trello.com


basecamp.com


LifeHacker - has a post on how to use Google's Calendar as a project management tool all on its own.
http://lifehacker.com/5918676/how-to-use-google-calendar-as-a-project-management-tool


Asana.com



Tuesday, August 27, 2013

What I wanted built-in, part 2

I am a responsible coder. Everywhere I’ve worked, if they haven’t had source control, I have championed the install of it. Even when it wasn’t possible, I have still campaigned to get it, because we all need insurance.

However.

This sense of responsibility? Not so much when in my test lab, but still, I do check in and check out to provide myself sanity. And prevent myself from stepping on myself. I just don’t do it as often as I would, since I’m not worried about other people getting in there.

(Well, I am, but that’s what firewalls are for.)

So, in trying to connect to Team Foundation Server, I was reminded that I’m going to need to install two MORE packages just to chat with my own TFS install from SSMS.

First up, I have:

Microsoft Visual Studio Team Explorer
http://www.microsoft.com/en-us/download/details.aspx?id=329


Then, I have to install:

Microsoft Visual Studio Team Foundation Server 2010 MSSCCI Provider 32-bit
http://visualstudiogallery.msdn.microsoft.com/bce06506-be38-47a1-9f29-d3937d3d88d6


Or, if I were on SQL 2012, I would need:

Microsoft Visual Studio Team Foundation Server 2012 MSSCCI Provider 32-bit
http://visualstudiogallery.msdn.microsoft.com/b5b5053e-af34-4fa3-9098-aaa3f3f007cd

And this is just so I can connect.

I want this built in – why isn’t this software on a web share as a part of the server install, so I don’t have to go back out to the internet and get it?

Tuesday, August 20, 2013

Open Source Project Management Part 2

In a previous post, I had written about needing to find a project management tool.

Really, though, what I want is integration.

The application workflow is really simple, actually:


  • Initialize the project requirements internally, based on my team's understanding of what we think the customer is asking for.
  • Review the task list and all dependencies with the customer in MS Project, or a tool (like those posted previously) that can export MS Project files.
  • Then, get all that now-approved info into some calendar tool, somehow, that we the project team all have access to. We don't all have to have the same *level* of access, mind you, just the ability get there somehow, easily.


And then I ran across this, which exports a MS Project file to Google Calendar. Now, I love the fact that this open-source tool does for me exactly what I need, and all I have to do to get my team on the calendar is send them the WebCal URL for the final calendar.

http://www.daball.me/2011/04/convert-microsoft-project-to-google.html


Tuesday, August 13, 2013

High Achieving

First, stop and go read this:

12 Ways to Spot a High Achiever

The point of this post is NOT to criticize his article.

Instead, what if you're just starting out? How would you do these things? How would you know how to recognize the signs that either you're really one of these people (while containing your ego there, champ), or to direct yourself to become the person described here?

I suggest, if you’re just starting out:

1. Ask, ask, ask. Ask for what you want. This does not mean be pushy, it means learn the difference between what you want, what you need, and how to not be passive aggressive about the difference between the two.

2. Learn when to cut and run. There are times where it makes sense, strategically, to quit, but this doesn’t just apply to jobs. It can be people, equipment, projects, etc.

3. Accept the reality around you as fact, and find a way to define what you’d like to see. Knowing the difference between where you are and where you want to go, but clearly, is the first step. From here, you can make a list of steps to get yourself from-here-to-there.

4. Help others. I’m putting this last, even though it really is first, because until I learned how to ask for what I wanted, I couldn’t really help others, because I wasn’t sure if I was helping myself, since I didn’t know what I wanted.

Tuesday, August 6, 2013

Open Source Project Management

I like open source software for some things.

Interoperability is king, though, when it comes to providing a lower-cost alternative to products that are marketed more strongly.

Two project management applications I've recently tried?

ProjectLibre
http://sourceforge.net/projects/projectlibre/

and

GanttProject
http://www.ganttproject.biz/

These are both installable applications for PC, Mac & *nix.

Having played with ProjectLibre for a while now, I was looking for two specific features in it, and GanttProject.
1. The ability to schedule the Summary / Parent task either separate from, OR as a result of the children. In other words, I first want to make the parent task (that is, the phases of the project), define the dependencies between them, and then go back and fill in the tasks per phases.

When I fill in the tasks per project phase, I want the tool to stretch the dates of the parent automatically. It also works for me if, like MS Project, there's a button I can flip that tells the tool "manual or auto" for the date scheduling.

I use this all the time for roughing in phases - much faster than tweaking task dates first - and to quickly communicate in Gantt chart form.


2. Date selection that works. The dates, although you can manually define them as what you want, don't work, and aren't user friendly. For example, in ProjectLibre, I can't just type in today's date, and the tool figures out that "Oh, hey! You want to use today? Sure! I'm just going to assume the normal start/end time for that, OK?"

Instead, it requires manually typing in the date in a programmer-decided format. NO! Bad coder! I want to type in the date, not have to be precise. I'm trying to manage a project here, and prototype phases with dates, not get stuck in a syntax war with my software tool.



Tuesday, July 30, 2013

Time-travelling DNS

I’m going to have to rebuild the DNS of my test lab domain.

At some point, it WILL happen.

When it does, what would I like to tell my future self?

IP addresses are irrelevant, because within the test network, those change all the time. (That would be the point of the home lab, wouldn’t it? To be able to build and rebuild as much as I want from within Workstation 9 and the VM’s?)

I think that I would like to remind myself that, when setting up a home lab for the first time, VMnet8 (NAT) is going to be your very bestest friend.

 

Open the VMware "Virtual Network Editor" to see which IP subnet’s configured and to also disable the “local DHCP service to distribute IP address to VMs”.

 _2013-07-25_21-45-33

Then, inside each VM? Go with IP address ranges
192.168.xx.3...50 (fixed, for the DC’s) and
192.168.xx.51...100 (for the clients & lab boxes).


The gateway address to use for configuring the Ethernet adapters in the VMs is 192.168.xx.2. You can find this by clicking on the “NAT Settings…” button in the Virtual Network Editor window.

NAT Settings_2013-07-25_21-52-21

 

Then, once all that’s done:
1. set each VM's DNS IPv4 server settings to point to the virtual DC

 DCDNS220101


2. on the DNS servers / DC’s, setup DNS forwarding to send DNS requests for other domains (that is, for the Internet) to the same IP as listed as “DNS Server” on the Host PC.

 

Last step, as always, is to prove it works. A quick test is this blog. If that succeeds, then check for updates using Windows Update.

Tuesday, July 23, 2013

Build a VMWare Workstation 9 Home / Test Lab

So I’m building a test lab at home.

This post is going to grow to become a directory of the issues, I think, that I post about that over time.

For now, here’s the plan:

Dual Windows Domain Controllers
Separately from the two DC’s, SQL Server 2012
Windows 8 Client PC

…and all on Workstation 9.

I’m building them in order to test SQL 2012 in a domain, of course, because I want to just jump in log in with Windows Authentication to SSAS, and I can’t do that without a domain.

I mean, I think I can – I’ve seen some articles about cobbling things together to do so, but honestly, I don’t really want to. Really.

I want to get as close to “best practices” as I can with this setup, since that’s what I’m expecting the exam(s) to cover.

Tuesday, July 16, 2013

Free software?

It really bugs me when free software functionality isn't included as a part of the base product.

http://windows.microsoft.com/en-gb/windows-live/essentials

For example, the Windows Essentials group of applications from Microsoft.

This seems, to me, for Windows 8 at least, to be not-quite-optional functionality that really has a place in the "installed by default category", with one large caveat. That is, if you're installing on a desktop.

And there is the other issue - why am I, with a mouse and keyboard on a laptop, having to suffer through gestures?

Perhaps in the dawning age of the tablet, I'm the odd man out for wanting a desktop, but really, let's face it. I LIKE having a mouse and keyboard. They allow me to function with an efficiency that currently just isn't possible any other way.

That said, I'd like my apps to be apps - getting redirected by a Fortune 500 company's website to their "full experience" on my Android phone is ridiculous. I also want my programs to be that - programs. Sized for the screen, not dependent on gestures, and for the love of Pete, to not assume a layout and control structure UI that requires a small screen to make any sense.


Tuesday, July 9, 2013

Public Data - Reference Post

These are some public data sources. 

This page is intended only as a reference for later use... I hope to update it as I'm able to categorize and collect mroe of these links.




Tuesday, May 21, 2013

How to make a date dimension

So I need to create a date dimension, and I refuse to use RBAR-y loops or cursors to do it.

That means I'm limiting myself, intentionally, to using a tally table (also sometimes called a numbers table).

I found the script by DustinRyan, URL included inline below, that did most of what I needed. However, the Day Of The Week In Month (DoWInMonth) column was filled by a loop, and that was going to violate the requirements for making this dimension.

Also, the election day query was using a nested loop, and that was going to violate the requirements for the making of this dimension.

Found below is my update of his script to use a tally table to dynamically generate the required column. On my development virtual machine, running on a laptop spinning at 5400 RPM, generating and inserting all 300 years of this data as an insert takes less than 5 seconds. Not bad.

Not bad at all.






-- Find 300 years of dates
-- This version created by brad mckuhen
-- http://www.bradmckuhen.com
-- Original from a date dimension script by DustinRyan, found here:
-- http://www.bidn.com/blogs/DustinRyan/bidn-blog/2667/create-date-dimension-script
PRINT convert(VARCHAR, getdate(), 113) --USED FOR CHECKING RUN TIME.

-- Need a DB everybody has
USE tempdb;
GO

-- Prevent unneeded network traffic
SET NOCOUNT ON;
GO

-- Clear any previous runs
IF object_id(N'tempdb..dimDate') IS NOT NULL
 DROP TABLE dimDate;

CREATE TABLE [dbo].[DimDate] (
 --[DateSK] [int] IDENTITY(1,1) NOT NULL--Use this line if you just want an autoincrementing counter AND COMMENT BELOW LINE 
 [DateSK] [int] NOT NULL --TO MAKE THE DateSK THE YYYYMMDD FORMAT USE THIS LINE AND COMMENT ABOVE LINE. 
 , [FullDate] [datetime] NOT NULL
 , [Day] [tinyint] NOT NULL
 , [DaySuffix] [varchar](4) NOT NULL
 , [DayOfWeek] [varchar](9) NOT NULL
 , [DayOfWeekNumber] [int] NOT NULL
 , [DayOfWeekInMonth] [tinyint] NOT NULL
 , [DayOfYearNumber] [int] NOT NULL
 , [RelativeDays] INT NOT NULL
 , [WeekOfYearNumber] [tinyint] NOT NULL
 , [WeekOfMonthNumber] [tinyint] NOT NULL
 , [RelativeWeeks] INT NOT NULL
 , [CalendarMonthNumber] [tinyint] NOT NULL
 , [CalendarMonthName] [varchar](9) NOT NULL
 , [RelativeMonths] INT NOT NULL
 , [CalendarQuarterNumber] [tinyint] NOT NULL
 , [CalendarQuarterName] [varchar](6) NOT NULL
 , [RelativeQuarters] INT NOT NULL
 , [CalendarYearNumber] INT NOT NULL
 , [RelativeYears] INT NOT NULL
 , [StandardDate] [varchar](10) NULL
 , [WeekDayFlag] BIT NOT NULL
 , [HolidayFlag] BIT NOT NULL
 , [OpenFlag] BIT NOT NULL
 , [FirstDayOfCalendarMonthFlag] BIT NOT NULL
 , [LastDayOfCalendarMonthFlag] BIT NOT NULL
 , [HolidayText] [varchar](50) NULL CONSTRAINT [PK_DimDate] PRIMARY KEY CLUSTERED ([DateSK] ASC) WITH (
  PAD_INDEX = OFF
  , STATISTICS_NORECOMPUTE = OFF
  , IGNORE_DUP_KEY = OFF
  , ALLOW_ROW_LOCKS = ON
  , ALLOW_PAGE_LOCKS = ON
  , FILLFACTOR = 100
  )
 ON [PRIMARY]
 ) ON [PRIMARY]
GO

--you could also set this line to getdate() if you wanted 300 years from today
DECLARE @CurrentDate DATE = '1/1/1800';
DECLARE @StartDate DATETIME = cast('12/31/1799' AS DATE);

INSERT INTO DimDate (
 [DateSK]
 , --TO MAKE THE DateSK THE YYYYMMDD FORMAT UNCOMMENT THIS LINE... Comment for autoincrementing. 
 [FullDate]
 , [Day]
 , [DaySuffix]
 , [DayOfWeek]
 , [DayOfWeekNumber]
 , [DayOfWeekInMonth]
 , [DayOfYearNumber]
 , [RelativeDays]
 , [WeekOfYearNumber]
 , [WeekOfMonthNumber]
 , [RelativeWeeks]
 , [CalendarMonthNumber]
 , [CalendarMonthName]
 , [RelativeMonths]
 , [CalendarQuarterNumber]
 , [CalendarQuarterName]
 , [RelativeQuarters]
 , [CalendarYearNumber]
 , [RelativeYears]
 , [StandardDate]
 , [WeekDayFlag]
 , [HolidayFlag]
 , [OpenFlag]
 , [FirstDayOfCalendarMonthFlag]
 , [LastDayOfCalendarMonthFlag]
 )
SELECT CONVERT(VARCHAR, calcdate, 112) AS [DateSK]
 , calcDate AS [FullDate]
 , DATEPART(DAY, calcDate) AS [Day]
 , CASE 
  WHEN DATEPART(DAY, calcDate) IN (
    11
    , 12
    , 13
    )
   THEN CAST(DATEPART(DAY, calcDate) AS VARCHAR) + 'th'
  WHEN RIGHT(DATEPART(DAY, calcDate), 1) = 1
   THEN CAST(DATEPART(DAY, calcDate) AS VARCHAR) + 'st'
  WHEN RIGHT(DATEPART(DAY, calcDate), 1) = 2
   THEN CAST(DATEPART(DAY, calcDate) AS VARCHAR) + 'nd'
  WHEN RIGHT(DATEPART(DAY, calcDate), 1) = 3
   THEN CAST(DATEPART(DAY, calcDate) AS VARCHAR) + 'rd'
  ELSE CAST(DATEPART(DAY, calcDate) AS VARCHAR) + 'th'
  END AS [DaySuffix]
 , CASE DATEPART(DW, CalcDate)
  WHEN 1
   THEN 'Sunday'
  WHEN 2
   THEN 'Monday'
  WHEN 3
   THEN 'Tuesday'
  WHEN 4
   THEN 'Wednesday'
  WHEN 5
   THEN 'Thursday'
  WHEN 6
   THEN 'Friday'
  WHEN 7
   THEN 'Saturday'
  END AS [DayOfWeek]
 , DATEPART(DW, CalcDate) AS [DayOfWeekNumber]
 --Occurance of this day in this month. If Third Monday then 3 and DOW would be Monday.
 , rank() OVER (
  PARTITION BY yearno
  , monthno
  , dow ORDER BY calcdate
  ) AS DOWInMonth
 , DATEPART(dy, CalcDate) AS [DayOfYearNumber] --Day of the year. 0 - 365/366
 , DATEDIFF(dd, @CurrentDate, CalcDate) AS [RelativeDays]
 , DATEPART(ww, CalcDate) AS [WeekOfYearNumber] --0-52/53
 , DATEPART(ww, CalcDate) + 1 - DATEPART(ww, CAST(DATEPART(mm, CalcDate) AS VARCHAR) + '/1/' + CAST(DATEPART(yy, CalcDate) AS VARCHAR)) [WeekOfMonthNumber]
 , DATEDIFF(ww, @CurrentDate, CalcDate) AS [RelativeWeeks]
 , DATEPART(MONTH, CalcDate) AS [CalendarMonthNumber] --To be converted with leading zero later.
 , DATENAME(MONTH, CalcDate) AS [CalendarMonthName]
 , DATEDIFF(MONTH, @CurrentDate, CalcDate) AS [RelativeMonths]
 , DATEPART(qq, CalcDate) AS [CalendarQuarterNumber] --Calendar quarter
 , CASE DATEPART(qq, CalcDate)
  WHEN 1
   THEN 'First'
  WHEN 2
   THEN 'Second'
  WHEN 3
   THEN 'Third'
  WHEN 4
   THEN 'Fourth'
  END AS [CalendarQuarterName]
 , DATEDIFF(qq, @CurrentDate, CalcDate) AS [RelativeQuarters]
 , DATEPART(YEAR, CalcDate) AS [CalendarYearNumber]
 , DATEDIFF(YEAR, @CurrentDate, CalcDate) AS [RelativeYears]
 , RIGHT('0' + convert(VARCHAR(2), MONTH(CalcDate)), 2) + '/' + Right('0' + convert(VARCHAR(2), DAY(CalcDate)), 2) + '/' + convert(VARCHAR(4), YEAR(CalcDate))
 , CASE DATEPART(DW, CalcDate)
  WHEN 1
   THEN 0
  WHEN 2
   THEN 1
  WHEN 3
   THEN 1
  WHEN 4
   THEN 1
  WHEN 5
   THEN 1
  WHEN 6
   THEN 1
  WHEN 7
   THEN 0
  END AS [WeekDayFlag]
 , 0 AS HolidayFlag
 , CASE DATEPART(DW, CalcDate)
  WHEN 1
   THEN 0
  WHEN 2
   THEN 1
  WHEN 3
   THEN 1
  WHEN 4
   THEN 1
  WHEN 5
   THEN 1
  WHEN 6
   THEN 1
  WHEN 7
   THEN 1
  END AS OpenFlag
 , CASE DATEPART(dd, CalcDate)
  WHEN 1
   THEN 1
  ELSE 0
  END AS [FirstDayOfCalendarMonthFlag]
 , CASE 
  WHEN DateAdd(day, - 1, DateAdd(month, DateDiff(month, 0, CalcDate) + 1, 0)) = CalcDate
   THEN 1
  ELSE 0
  END AS [LastDayOfCalendarMonthFlag]
FROM (
 -- To fuel the RANK() I use to get the dynamic 
 -- DoWinMonth value, I calculate the necessary pieces here
 SELECT [Surrogate Key] AS IDNo
  , @StartDate + [Surrogate Key] AS CalcDate
  , datepart(DW, @StartDate + [Surrogate Key]) AS DoW
  , year(@StartDate + [Surrogate Key]) AS YearNo
  , month(@StartDate + [Surrogate Key]) AS MonthNo
 FROM (
  -- This is the tally table on which the whole thing is built
  SELECT TOP (
    SELECT cast(365.25 * 300 AS BIGINT)
    ) ROW_NUMBER() OVER (
    ORDER BY getdate()
    ) AS [Surrogate Key]
  FROM sys.syscolumns s1
   , sys.syscolumns s2
  ) j
 ) k
-- Get the results in a predictable order
ORDER BY [DateSK];

--Add HOLIDAYS --------------------------------------------------------------------------------------------------------------
-- New Years Day --------------------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'New Year''s Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 1
 AND [DAY] = 1

--Set OpenFlag = 0 if New Year's Day is on weekend 
UPDATE dbo.DimDate
SET OpenFlag = 0
WHERE DateSK IN (
  SELECT CASE 
    WHEN DayOfWeek = 'Sunday'
     THEN DATESK + 1
    END
  FROM DimDate
  WHERE CalendarMonthNumber = 1
   AND [DAY] = 1
  )

--Martin Luther King Day --------------------------------------------------------------------------------------- 
--Third Monday in January starting in 1983 
UPDATE DimDate
SET HolidayText = 'Martin Luther King Jr. Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 1 --January 
 AND [Dayofweek] = 'Monday'
 AND CalendarYearNumber >= 1983 --When holiday was official 
 AND [DayOfWeekInMonth] = 3 --Third X day of current month. 
GO

--President's Day --------------------------------------------------------------------------------------- 
--Third Monday in February. 
UPDATE DimDate
SET HolidayText = 'President''s Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 2 --February 
 AND [Dayofweek] = 'Monday'
 AND [DayOfWeekInMonth] = 3 --Third occurance of a monday in this month. 
GO

--Memorial Day ---------------------------------------------------------------------------------------- 
--Last Monday in May 
UPDATE dbo.DimDate
SET HolidayText = 'Memorial Day'
 , HolidayFlag = 1
 , OpenFlag = 0
FROM DimDate
WHERE DateSK IN (
  SELECT MAX([DateSK])
  FROM dbo.DimDate
  WHERE [CalendarMonthName] = 'May'
   AND [DayOfWeek] = 'Monday'
  GROUP BY CalendarYearNumber
   , [CalendarMonthNumber]
  )

--4th of July --------------------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'Independance Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 7
 AND [DAY] = 4

--Set OpenFlag = 0 if July 4th is on weekend 
UPDATE dbo.DimDate
SET OpenFlag = 0
WHERE DateSK IN (
  SELECT CASE 
    WHEN DayOfWeek = 'Sunday'
     THEN DATESK + 1
    END
  FROM DimDate
  WHERE CalendarMonthNumber = 7
   AND [DAY] = 4
  )

--Labor Day ------------------------------------------------------------------------------------------- 
--First Monday in September 
UPDATE dbo.DimDate
SET HolidayText = 'Labor Day'
 , HolidayFlag = 1
 , OpenFlag = 0
FROM DimDate
WHERE DateSK IN (
  SELECT MIN([DateSK])
  FROM dbo.DimDate
  WHERE [CalendarMonthName] = 'September'
   AND [DayOfWeek] = 'Monday'
  GROUP BY CalendarYearNumber
   , [CalendarMonthNumber]
  )

--Columbus Day------------------------------------------------------------------------------------------ 
--2nd Monday in October 
UPDATE dbo.DimDate
SET HolidayText = 'Columbus Day'
 , HolidayFlag = 1
 , OpenFlag = 0
FROM DimDate
WHERE DateSK IN (
  SELECT MIN(DateSK)
  FROM dbo.DimDate
  WHERE [CalendarMonthName] = 'October'
   AND [DayOfWeek] = 'Monday'
   AND [DayOfWeekInMonth] = 2
  GROUP BY CalendarYearNumber
   , [CalendarMonthNumber]
  )

--Veteran's Day -------------------------------------------------------------------------------------------------------------- 
UPDATE DimDate
SET HolidayText = 'Veteran''s Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE DateSK IN (
  SELECT CASE 
    WHEN DayOfWeek = 'Saturday'
     THEN DateSK - 1
    WHEN DayOfWeek = 'Sunday'
     THEN DateSK + 1
    ELSE DateSK
    END AS VeteransDateSK
  FROM DimDate
  WHERE [CalendarMonthNumber] = 11
   AND [DAY] = 11
  )
GO

--THANKSGIVING -------------------------------------------------------------------------------------------------------------- 
--Fourth THURSDAY in November. 
UPDATE DimDate
SET HolidayText = 'Thanksgiving Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 11
 AND [DAYOFWEEK] = 'Thursday'
 AND [DayOfWeekInMonth] = 4
GO

--CHRISTMAS ------------------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'Christmas Day'
 , HolidayFlag = 1
 , OpenFlag = 0
WHERE [CalendarMonthNumber] = 12
 AND [DAY] = 25

--Set OpenFlag = 0 if Christmas on weekend 
UPDATE dbo.DimDate
SET OpenFlag = 0
WHERE DateSK IN (
  SELECT CASE 
    WHEN DayOfWeek = 'Sunday'
     THEN DATESK + 1
    WHEN Dayofweek = 'Saturday'
     THEN DateSK - 1
    END
  FROM DimDate
  WHERE CalendarMonthNumber = 12
   AND DAY = 25
  )

-- Valentine's Day --------------------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'Valentine''s Day'
WHERE CalendarMonthNumber = 2
 AND [DAY] = 14

-- Saint Patrick's Day ----------------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'Saint Patrick''s Day'
WHERE [CalendarMonthNumber] = 3
 AND [DAY] = 17
GO

--Mother's Day --------------------------------------------------------------------------------------- 
--Second Sunday of May 
UPDATE DimDate
SET HolidayText = 'Mother''s Day' --select * from DimDate 
WHERE [CalendarMonthNumber] = 5 --May 
 AND [Dayofweek] = 'Sunday'
 AND [DayOfWeekInMonth] = 2 --Second occurance of a monday in this month. 
GO

--Father's Day --------------------------------------------------------------------------------------- 
--Third Sunday of June 
UPDATE DimDate
SET HolidayText = 'Father''s Day' --select * from DimDate 
WHERE [CalendarMonthNumber] = 6 --June 
 AND [Dayofweek] = 'Sunday'
 AND [DayOfWeekInMonth] = 3 --Third occurance of a monday in this month. 
GO

--Halloween 10/31 ---------------------------------------------------------------------------------- 
UPDATE dbo.DimDate
SET HolidayText = 'Halloween'
WHERE [CalendarMonthNumber] = 10
 AND [DAY] = 31

--Election Day-------------------------------------------------------------------------------------- 
--The first Tuesday after the first Monday in November. 
UPDATE tues
SET HolidayFlag = 1
 , HolidayText = 'Election Day'
FROM dimdate AS tues
INNER JOIN dimdate AS mon
 ON tues.fulldate = mon.fulldate + 1
WHERE mon.CalendarMonthNumber = 11
 AND mon.[DayOfWeek] = 'Monday'
 AND mon.DayOfWeekInMonth = 1
GO

-------------------------------------------------------------------------------------------------------- 
PRINT CONVERT(VARCHAR, GETDATE(), 113) --USED FOR CHECKING RUN TIME.

--DimDate indexes--------------------------------------------------------------------------------------------- 
CREATE UNIQUE NONCLUSTERED INDEX [IDX_DimDate_Date] ON [dbo].[DimDate] ([FullDate] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_Day] ON [dbo].[DimDate] ([Day] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_DayOfWeek] ON [dbo].[DimDate] ([DayOfWeek] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_DOWInMonth] ON [dbo].[DimDate] ([DayOfWeekInMonth] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_DayOfYear] ON [dbo].[DimDate] ([DayOfYearNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_WeekOfYear] ON [dbo].[DimDate] ([WeekOfYearNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_WeekOfMonth] ON [dbo].[DimDate] ([WeekOfMonthNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_Month] ON [dbo].[DimDate] ([CalendarMonthNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_MonthName] ON [dbo].[DimDate] ([CalendarMonthName] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_Quarter] ON [dbo].[DimDate] ([CalendarQuarterNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_QuarterName] ON [dbo].[DimDate] ([CalendarQuarterName] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_DimDate_Year] ON [dbo].[DimDate] ([CalendarYearNumber] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IDX_dim_Time_HolidayText] ON [dbo].[DimDate] ([HolidayText] ASC)
 WITH (
   PAD_INDEX = OFF
   , STATISTICS_NORECOMPUTE = OFF
   , SORT_IN_TEMPDB = OFF
   , IGNORE_DUP_KEY = OFF
   , DROP_EXISTING = OFF
   , ONLINE = OFF
   , ALLOW_ROW_LOCKS = ON
   , ALLOW_PAGE_LOCKS = ON
   , FILLFACTOR = 90
   ) ON [PRIMARY]

PRINT convert(VARCHAR, getdate(), 113) --USED FOR CHECKING RUN TIME.
/*
-- Holiday Validation Query
select count(1), HolidayText 
from dimdate 
where HolidayFlag = 1
group by HolidayText
having count(1) >= 1

*/