Friday, 8 April 2011

Powershell: ISO Date Format

I've been looking to generate some database scripts on a regular basis and wanted to keep them in folders based upon date. As is my want, I like to keep the dates in ISO format so that they can be easily ordered through windows explorer.

The main problem I found using the DatePart functions in Powershell was that for the first 9days/months of the year, it returns just a single digit rather than padded with a zero (e.g 201148 rather than 20110408). I could have got round it with some extra string manipulation, but, a little bit of guidance from @theBoardz showed that you can just use the ToString() method on the get-date Cmdlet.

$dt = (get-date).ToString("yyyy" + (Get-date).ToString("mm" + (Get-date).ToString("dd"

UPDATE: can actually do this in a single line! Thanks Alan!

(get-date).ToString("yyyyMMdd")

Wednesday, 6 April 2011

T-SQL: Get Updated Value

There are many ways to get the value that a column has just been updated to. Often, it'll be being set to an explicit value that you already know, but there are occasions (eg GETDATE() and using Functions) where you might not know for sure what the value has been updated to.

You could use the OUTPUT clause available in SQL2005 and later and for auto-increments you have SCOPE_IDENTITY and friends.

However, here's a neat little trick that I've seen once or twice before and involves setting the variable in the SET clause of your UPDATE statement and looks like this:

CREATE TABLE dbo.Beatles
(IdVal INT, Nm NVARCHAR(55))
GO
INSERT INTO dbo.Beatles SELECT 1, 'John'
INSERT INTO dbo.Beatles SELECT 2, 'Paul'
INSERT INTO dbo.Beatles SELECT 3, 'George'
INSERT INTO dbo.Beatles SELECT 4, 'Ronny'
GO
DECLARE @NewName NVARCHAR(55)

UPDATE dbo.Beatles
SET @NewName = Nm = 'Ringo' -- look at this funky syntax!!
WHERE IdVal = 4

SELECT @NewName
SELECT * FROM dbo.BeatlesWHERE IdVal = 4


Ok, so its not going to set the world on fire, but its something that you may come across so can't hurt to be aware of.

Friday, 1 April 2011

T-SQL: Get first day of the current month

You get a lot of people asking to find out first/last days of months based upon a certain date. Essentially, you can work out nearly anything you want just by getting day 1 of your current month and then using the date functions.

Although this is posted in hundreds of places on the web, for my own sanity as much as anything i'm going to post it here too.

DECLARE @TestDate DATE = '20110417';

SELECT DATEADD(M, DATEDIFF(M, 0, @TestDate), 0) AS NewDate;

-- NewDate
-- 2011-04-01 00:00:00.000
/* add this crazy stuff in so i can use syntax highlighter