|
|
I’ve been a stickler for default names since reading Jason Strate’s (blog/twitter) post on cleaning up auto-generated names. Today I had to create a non-nullable column with a default – can I do it in one step? Yep – here’s an example:
ALTER TABLE <<TABLENAME>> ADD <<COLUMNNAME>> <<TYPE>> NOT NULL CONSTRAINT <<DEFAULTNAME>> DEFAULT (<<Value>>)
Here’s the example in action:
Create table Testtable
(id int)
Insert Testtable Values (1),(2),(3),(4),(5)
ALTER TABLE Testtable ADD DefaultTest BIT NOT NULL CONSTRAINT DF_Testtable_DefaultTest DEFAULT (0)
Select * from Testtable
--/*Now to drop this column, do it in this order */
Alter table Testtable alter column DefaultTest bit null
Alter table Testtable Drop constraint DF_Testtable_DefaultTest
Alter table Testtable DROP column DefaultTest
Challenges:
- Coding on Project B
- Gave demonstration of Powershell to my DBA team on how to:
Good Reading from the Week:
The Week Ahead:
Goals for the Year – 3 Ps – (These are my year long goals that I’ll report on each week to keep me focused, read about them here.)
- PASSMN – not much: C for the past week
- Powershell – A- for the past week – gave demo, started reading two books on it…
- Present – Gave demo on Powershell to DBA team: B for the week.

Here’s a script that will create an insert/update statement for a list of values. This is a major time saver for me – I have to create scripts like this for people fairly often. It is designed for a simple look up table with an ID column and a some sort of description column such as this….
Create table TestAndysAwesomeInsertGenerator
(TestID int,
TestDesc varchar(50),
TSTimestamp timestamp)
Now let’s say you needed to generate insert and/or update statements for this list of values like this:
- This is line1
- This is line2
- This is line3
- etc…
You could enter the data into a table, then script out the insert statements and worry about the update statements later – or create row update/insert and do a lot of copying and pasting and editing, etc. Well here’s a shortcut I came up with…use this script that creates a script.
Set nocount on
--/*Declare the variables.*/
Declare @ScriptOutput varchar(Max),
@tablename varchar(255),
@Col1 varchar(255),
@Col2 varchar(255),
@Counter1 int,
@Counter2 int,
@DescValue varchar(255)
Declare @ValuesTable table ([ID] int IDENTITY(1,1), [Description] varchar(255))
Declare @FinalScript table ([Script] varchar(max))
----------------------------------------------------------------------------------------------
--/* This is the section that needs to be changed each time for each table and the values. */
----------------------------------------------------------------------------------------------
Set @tablename = 'TestAndysAwesomeInsertGenerator'
Insert @ValuesTable
Values('This is line1'),
('This is line2'),
('This is line3'),
('etc...')
--------------------------------------------------------------------------------------------
--/* That's it - everything else should be automatic - if it's a simple table. */
--------------------------------------------------------------------------------------------
Select @Counter1 = COUNT(*) from @ValuesTable
Set @Counter2 = 1
--/* if the table has more columns, hard code the column names in here. */
Select @Col1 = SC.name from sys.columns SC
Join sys.types ST on ST.user_type_id = SC.user_type_id
where SC.object_id = OBJECT_ID(@tablename)
and ST.name like '%int%'
Select @Col2 = SC.name from sys.columns SC
Join sys.types ST on ST.user_type_id = SC.user_type_id
where SC.object_id = OBJECT_ID(@tablename)
and ST.name like '%char%'
--Manipulate the string...
Set @ScriptOutput =
'IF NOT EXISTS (Select 1 from <<TableName>> where <<Col1>> = <<IDVal>>)
Begin
Insert <<TableName>> (<<Col1>>, <<Col2>>) Values (<<IDVal>>, <<DescVal>>)
End
Else
Begin
IF NOT EXISTS (Select 1 from <<TableName>> where <<Col1>> = <<IDVal>> and <<Col2>> = <<DescVal>>)
Update <<TableName>> Set <<Col2>> = <<DescVal>> where <<Col1>> = <<IDVal>>
End
'
Select @ScriptOutput = Replace(Replace(Replace(@ScriptOutput, '<<TableName>>', @tablename), '<<Col1>>', @Col1), '<<Col2>>', @Col2)
Insert @FinalScript Select '/* Begin Codes for ' + @tablename + '*/'
While @Counter2 <= @Counter1
Begin
Select @DescValue = '''' + [Description] + '''' from @ValuesTable where [ID] = @Counter2
Insert @FinalScript
Select Replace(Replace(@ScriptOutput, '<<IDVal>>', @Counter2), '<<DescVal>>', @DescValue)
Select @Counter2 = @Counter2 + 1
End
Insert @FinalScript Select '/* End Codes for ' + @tablename + '*/'
Select * from @FinalScript
Here is the output of this script:
/* Begin Codes for TestAndysAwesomeInsertGenerator*/
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 1)
Begin
Insert TestAndysAwesomeInsertGenerator (TestID, TestDesc) Values (1, 'This is line1')
End
Else
Begin
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 1 and TestDesc = 'This is line1')
Update TestAndysAwesomeInsertGenerator Set TestDesc = 'This is line1' where TestID = 1
End
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 2)
Begin
Insert TestAndysAwesomeInsertGenerator (TestID, TestDesc) Values (2, 'This is line2')
End
Else
Begin
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 2 and TestDesc = 'This is line2')
Update TestAndysAwesomeInsertGenerator Set TestDesc = 'This is line2' where TestID = 2
End
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 3)
Begin
Insert TestAndysAwesomeInsertGenerator (TestID, TestDesc) Values (3, 'This is line3')
End
Else
Begin
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 3 and TestDesc = 'This is line3')
Update TestAndysAwesomeInsertGenerator Set TestDesc = 'This is line3' where TestID = 3
End
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 4)
Begin
Insert TestAndysAwesomeInsertGenerator (TestID, TestDesc) Values (4, 'etc...')
End
Else
Begin
IF NOT EXISTS (Select 1 from TestAndysAwesomeInsertGenerator where TestID = 4 and TestDesc = 'etc...')
Update TestAndysAwesomeInsertGenerator Set TestDesc = 'etc...' where TestID = 4
End
/* End Codes for TestAndysAwesomeInsertGenerator*/
This takes care of the data – here are some test cases, run one or both of these scripts, then re-run the output script above and the data will be back to what you initially set it for.
Delete from TestAndysAwesomeInsertGenerator where TestID = 2
--
Update TestAndysAwesomeInsertGenerator set testdesc = 'Row Updated' where testid = 4
--
Select * from TestAndysAwesomeInsertGenerator
Inspired by Jason Strate’s (Blog| Twitter) post “PowerShell: Download List of SQL Server MVPs”, which was inspired by John Samson’s (Blog| Twitter) post “The Best Database Administrators Automate Everything” – which also inspired me. I decided to create a Powershell script to grab my starred items in Google Reader and format them into an HTML Page with links for my Weekly Challenges/Good Reading Posts.
The Set Up
I had an HTML template created for these pages, so I split it into three parts:
- The portion above the Good Reading and Links – I saved this to a text file located at “c:\temp\TopTemplate.txt”
- The Good Reading and Links
- The portion below the Good reading and Links – I saved this to a text file located at “c:\temp\BotTemplate.txt”
I then looked at my public page for Starred Items on Google Reader. Note this script works for any public listing on Google Reader, so I can create a Public Page and change the URL in this script and it still works.
The Code
##------------------------##
##--Reader Starred Items--##
##------------------------##
$webclient = New-Object system.net.webclient
$SourceFile = "c:\temp\Reader.txt"
$HTMLPage = "C:\temp\GoodReading.txt"
$TopTemplate = "c:\temp\TopTemplate.txt"
$BotTemplate = "c:\temp\BotTemplate.txt"
$url="http://www.google.com/reader/shared/user/14135896925018987441/state/com.google/starred"
$webclient.DownloadFile($url,$SourceFile)
#Get the titles with links
$itemtitle = Select-String $SourceFile -pattern "h2 class=""item-title""" |
% {$_ -replace "<div id=""items""><div class=""item""><h2 class=""item-title""><div class="""">", ""} |
% {$_ -replace "</div></h2>", ""} |
% {$_ -replace "<div class=""clear""></div></div></div> <div class=""item""><h2 class=""item-title""><div class="""">", ""} |
% {$_ -replace "c:\\temp\\Reader\.txt:[0-9]*:", ""}
#Get the details with links
$iteminfo = Select-String $SourceFile -pattern "<div class=""item-info"">" |
% {$_ -replace "c:\\temp\\Reader\.txt:[0-9]*:<div class=""item-info"">", ""} |
% {$_ -replace "</div>", ""}
$i=0
$FinalContent = " "
foreach ($t in $itemtitle)
{$FinalContent= $FinalContent +"<li>"+ $itemtitle[$i] + " " + $iteminfo[$i]+"</li>" + "`r`n "
$i++}
$FinalContent = "<p><strong>Good Reading from the Week</strong>:</p>" + "`r`n" + "<ul>" + "`r`n" + $FinalContent + "`r`n" + "</ul>"
$TopTemp = Get-Content $TopTemplate
$BotTemp = Get-Content $BotTemplate
$FinalContent = $TopTemp + $FinalContent + $BotTemp
Set-Content $HTMLPage $FinalContent
invoke-item $HTMLPage
When the script completes, I simply update a couple of statuses and change the photo and it’s good to go!
Challenges:
- Updated this site:
- Feedburner Feed – new RSS feed here – Please update – I’ll post on just this when I’m ready 100%.
- Updated the Twitter, Subscribe and Search Widgets
- Added The SQLQuill Daily
- Added a link to Pass MN
- Pitchers and Catchers reported, so I updated the logo – temporarily.
- On Call – Log Shipping Issue that took some midnight hours
- Coding on Project B
- A bit of performance tuning – I had to pull out the “Image an index is a like…an index in a book and you are trying to look up something that is either a 0 or a 1, would the index of a book be helpful?”
- Attended Pass MN’s meeting – the slides from the presentations are found at the Pass MN site under the Resources tab.
Good Reading from the Week:
The Week Ahead:
- Project B coding
- New procs for new tables
- Syncing environments or verifying environments are level set
- Syndicate this blog to SQLServerPedia – it’s time to get more traffic.
Goals for the Year – 3 Ps – (These are my year long goals that I’ll report on each week to keep me focused, read about them here.)
- PASSMN – Added some content, attended Tim Plas’s presentation: B for the past week
- Powershell – A- for the past week – Used Powershell to:
- Get servers from web page script (more to come on that)
- Started working with PowerGUI.
- Present - N/A: Inc for the week.

I got into a bit of a situation today. There were some performance issues in our performance testing environment and my changes (and a few others) were finally being tested. I was also told by various levels of management not to work on this project – concentrate my efforts on Project B. All I could think was my changes had to be using the correct indexes – how could I tell with out a lot of work – DMVs on index usage stats. I fired up google and found this from mssqltips.com. I changed the select a little and added the fairly accurate way to get row counts as a CTE. Here’s what I came up with:
;With RowCounts_CTE as
(SELECT
so.id,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.id, so.name)
SELECT OBJECT_NAME(S.[OBJECT_ID]) AS [OBJECT NAME],
I.[NAME] AS [INDEX NAME],
RC.[RowCount],
USER_SEEKS,
USER_SCANS,
USER_LOOKUPS,
USER_UPDATES
FROM SYS.DM_DB_INDEX_USAGE_STATS AS S
INNER JOIN SYS.INDEXES AS I
ON I.[OBJECT_ID] = S.[OBJECT_ID]
AND I.INDEX_ID = S.INDEX_ID
Join RowCounts_CTE RC on RC.id = S.object_id
WHERE OBJECTPROPERTY(S.[OBJECT_ID],'IsUserTable') = 1
Order by 1
Reminder – PASSMN Meeting today – 3 PM Today!
Location: 8300 Norman Center Drive, Bloomington, MN 55437
Sponsor: Digineer

RSVP Here
Agenda:
- 2:45-3:00 : Registration / hospitality / networking
- 3:00-3:15 : Announcements etc.
- 3:15-5:00 : Tim Plas: High Availability & DR Options for SQL Server
Live Meeting Info:
Presentation:
High Availability & DR Options for SQL Server
A comparison of SQL HA & DR options, by a practitioner who has implemented & managed all the SQL HA and DR approaches (& various combinations thereof). Tim is an operational DBA, charged with keeping SQL servers up & running & optimized, for managed-services customers. We will compare trade-offs between the various SQL HA & DR options: for complexity, usability, hardware requirements, licensing, failover speed, initial costs, ongoing support costs, staff skill requirements, etc.
Also, as you may be aware, Microsoft has announced a set of very powerful “AlwaysOn” features for the upcoming version of SQL (“Denali”), features popularly referred to as “HADRON” (“High Availability Disaster Recovery always ON”). We’ll provide a brief overview of those features now, and will have a full presentation on that later in the year.
Tim Plas is a Principal Consultant at Virteva, in Mpls. His current focus areas are operational-DBA services, storage, cloud computing, & providing level-3 escalation support for IT managed services. Previous specialties in his 25+ years in the IT field have covered Citrix/TS (app hosting), LAN’s / WAN’s / network security, DB architecture, systems analysis & design, app development, systems-level programming, & various IT mgmt roles. Tim has held a variety of MS certifications since 1994.
Challenges:
- Coding on Project B
- Moved Code in TFS
- Gave demonstration of new database DDL triggers and deploy process
- Used Powershell to find files with columns, move files in crunch time – there was an issue I needed resolved ASAP.
Good Reading from the Week:
The Week Ahead:
Goals for the Year – 3 Ps – (These are my year long goals that I’ll report on each week to keep me focused, read about them here.)
- PASSMN – February coming up, tweeked web site: B+ for the past week
- Powershell – A for the past week – Used Powershell to:
- move files around for TFS changes
- find procedures with columns
- get links list above (more to come on that)
- Present – Gave demo on DDL triggers and deploy process to DBA team, Gave overview of schema changes for Project B to others: B+ for the week.

Challenges:
- Coding on Project B
- A couple of fires with other projects
- Used Powershell to manage files in TFS
Good Reading from the Week:
The Week Ahead:
- Project B coding.
- Project A issues?
- T-SQL Tuesday
Goals for the Year – 3 Ps – (These are my year long goals that I’ll report on each week to keep me focused, read about them here.)
- PASSMN – February Meeting details ironed out: B+ for the past week
- Powershell – Wrote scripts move files around, worked on the Out-file: A for the past week
- Present – – No progress – NA for the past week

Location: 8300 Norman Center Drive, Bloomington, MN 55437
Sponsor: Digineer
RSVP Here
Agenda:
- 2:45-3:00 : Registration / hospitality / networking
- 3:00-3:15 : Announcements etc.
- 3:15-5:00 : Tim Plas: High Availability & DR Options for SQL Server
Presentation:
High Availability & DR Options for SQL Server
A comparison of SQL HA & DR options, by a practitioner who has implemented & managed all the SQL HA and DR approaches (& various combinations thereof). Tim is an operational DBA, charged with keeping SQL servers up & running & optimized, for managed-services customers. We will compare trade-offs between the various SQL HA & DR options: for complexity, usability, hardware requirements, licensing, failover speed, initial costs, ongoing support costs, staff skill requirements, etc.
Also, as you may be aware, Microsoft has announced a set of very powerful “AlwaysOn” features for the upcoming version of SQL (“Denali”), features popularly referred to as “HADRON” (“High Availability Disaster Recovery always ON”). We’ll provide a brief overview of those features now, and will have a full presentation on that later in the year.
Tim Plas is a Principal Consultant at Virteva, in Mpls. His current focus areas are operational-DBA services, storage, cloud computing, & providing level-3 escalation support for IT managed services. Previous specialties in his 25+ years in the IT field have covered Citrix/TS (app hosting), LAN’s / WAN’s / network security, DB architecture, systems analysis & design, app development, systems-level programming, & various IT mgmt roles. Tim has held a variety of MS certifications since 1994.
|
|