SQLvariations: SQL Server, a little PowerShell, maybe some Hyper-V Rotating Header Image

SSMS

SQL Server Management Studio

SQLServer:\SQL\Databases\Tables> Dir

Getting started talking to your SQL Servers in the PowerShell 2.0 ISE

By now hopefully you’ve noticed that SQL Server 2008 comes with PowerShell all over the place.  Just about anything you click on in Object Explorer has “Start PowerShell” and you can even execute PowerShell steps in SQL Agent Jobs. 

You may be wondering why on Earth you would want to “Start PowerShell” in the first place.  I’ll show you one thing today and then expand on that in later blog posts but today I wanted to tell you how to run PowerShell in something a little more organized than a command prompt window.  The first thing I’d like you to do is open up SSMS, connect to an instance and Right-Click the Databases folder > then select Start PowerShell.  A command prompt window should open up and from there you can talk to your SQL Server instance as if was a drive on your machine:

LaunchSQLPS

The SQLPS window that just opened up is PowerShell 1.0 with a special ‘expansion pack’ that allows it to talk to SQL Server in a way that PowerShell alone can’t.  So now that we’ve got that covered I want to show you how to do the same thing in PowerShell 2.0’s ISE. 

Go to Start > All Programs > Accessories > Windows PowerShell > Windows PowerShell ISE

Copy the code from the bottom and step through it like I did in this picture.  When you’re done you will be able to drill down to tables like they were just folders directories on your hard drive.  If you aren’t running Windows 7 (upgrade already!) check this post and see if you’re operating system is eligible.

ISE_SQL

When you get to the part where you do “get-psdrive” for the second time you should now see the SQL Server on your local machine.  If you haven’t figured out yet, this is only going to work if you have SQL Server installed on your local machine. 

#Before
get-psdrive

#Snapins that are running
get-pssnapin
#Snapins that you can load
get-pssnapin -registered

#Go ahead and add the SQL Snapins
add-pssnapin SqlServerCmdletSnapin100
add-pssnapin SqlServerProviderSnapin100

#New Resource
get-psdrive

#What can we do with that?
cd SQLSERVER:\SQL\YourComputerName\YourInstanceName\DATABASES\ADVENTUREWORKS\TABLES

Now that we have done all of that we can do something that I have seen mentioned several places but I think that Allen White’s blog post explains it the best (here’s my version of it).  You can now create a variable and populate it with one the DDL structures in your database and from there generate a Create script for it like so:

$PTH = get-item Production.TransactionHistory
$PTH.Script()

Your output should look something like this:
PS SQLSERVER:\sql\WIN7\DATABASES\ADVENTUREWORKS\TABLES> $PTH = get-item Production.TransactionHistory
$PTH.Script()
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[TransactionHistory](
 [TransactionID] [int] IDENTITY(100000,1) NOT NULL,
 [ProductID] [int] NOT NULL,
 [ReferenceOrderID] [int] NOT NULL,
 [ReferenceOrderLineID] [int] NOT NULL,
 [TransactionDate] [datetime] NOT NULL,
 [TransactionType] [nchar](1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [Quantity] [int] NOT NULL,
 [ActualCost] [money] NOT NULL,
 [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

And that’s it for this edition of how to do something when you open up the PowerShell 2.0 ISE.  Next we’ll do something more useful I promise.

Lunch-n-Learn #01: SQL Server 2005 Features

Yesterday I did a quick Lunch-n-Learn here at my company on a few SQL Server 2005 features and this post is just a follow-up to remind everyone what we saw and where you can find those features.  I will try to still make this useful for those of you who didn’t attend.

0:  To make any of these code examples work please download and install the Sample Databases for SQL Server.  (Don’t worry, they’re pretty small.)

  1. The first thing that you folks saw was the intelli-sense where as I was typing the name of a table and SQL Server Management Studio (SSMS) was finishing the table name for me.  That was the only SQL Server 2008 exclusive feature that you saw in the entire session.  You can only see this if you have the SSMS 2008 client pointed to a SQL 2008 db.
  2. I showed you guys how to find out the name of every table and column of the db that you are in using the system views:
    SELECT *
    FROM INFORMATION_SCHEMA.TABLES
  3. SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS

  4. Ticks!  How did this apostrophe get into our db?  And how do we get it out?
    SELECT  [Comments] ,[ProductReviewID] ,[ProductID] ,[ReviewerName] ,[ReviewDate] ,[EmailAddress] ,[Rating] ,[ModifiedDate]
      FROM [AdventureWorks].[Production].[ProductReview]
  5. Well you just use 2 ticks to insert a single tick.  Said again, you use “’’” to insert “” into SQL. Here’s an example from the AdventureWorks database:
    SET IDENTITY_INSERT [Production].[ProductReview] ON
    INSERT [Production].[ProductReview] ([ProductReviewID], [ProductID], [ReviewerName], [ReviewDate], [EmailAddress], [Rating], [Comments], [ModifiedDate])
    VALUES
    (6, 709, ‘John Smith’, CAST(0×0000941800000000 AS DateTime), “>‘john@fourthcoffee.com’, 5
    , ‘I can”t believe I”m singing the praises of a pair of socks, but I just came back from a grueling
    3-day ride and these socks really helped make the trip a blast. They”re lightweight yet really cushioned my feet all day.
    The reinforced toe is nearly bullet-proof and I didn”t experience any problems with rubbing or blisters like I have with
    other brands. I know it sounds silly, but it”s always the little stuff (like comfortable feet) that makes or breaks a long trip.
    I won”t go on another trip without them!’
    , CAST(0×0000941800000000 AS DateTime))
    SET IDENTITY_INSERT [Production].[ProductReview] OFF

    And we can get it out like this:
    UPDATE [Production].[ProductReview]
       SET Comments = REPLACE(Comments, ””, )
     WHERE ProductReviewID = 6

  6. To make your keyboard as useful as mine what you do is open up SSMS click on Tool > Options > Environment > Keyboard >and add the commands that you would like the corresponding shortcut key to execute.
    image
  7. What Exactly is XACT_ABORT?  When XACT_ABORT is ON SQL Server will stop and roll back the transaction as soon as it hits an error; it won’t continue processing all the way to the end.  “When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing.”
    Use this script to see it work for yourself.
  8. The next feature that I showed you was how you can create an Identity Column for the data you are  selecting without having to insert the data into a table by using the ROW_NUMBER() function.  I mentioned several other features along with that one and I will demo those features in our next Lunch-n-Learn.  In the meantime here’s a script that will show you it do 4 different row numbers on 4 different fields all at the same time.
    /* SQL Purists: please don’t freak out at this script, I’m just showing functionality*/
    SELECT TOP 500 *
                 ROW_NUMBER
    () OVER (ORDER BY AvgCPUTime DESC) AS 'AVG Time Rank'
          
    ,     ROW_NUMBER() OVER (ORDER BY total_cpu_time DESC) AS 'Total CPU Rank'
          
    ,     ROW_NUMBER() OVER (ORDER BY total_duration_time DESC) AS 'Total Duration Rank'
          
    ,     ROW_NUMBER() OVER (ORDER BY total_execution_count DESC) AS 'Total Executions Rank'
          
    , a.TEXT AS 'StatementText'
          
    , a.total_cpu_time
          
    , a.total_execution_count
          
    , a.total_duration_time
          
    , a.AvgCPUTime
          
    , a.number_of_statements
          
    , a.plan_handle
          
    , SUBSTRING(a.TEXT, 1, 100) AS 'hundy', a.name
      
    FROM (
          
    SELECT
                
    sql_text.TEXT,
              
    SUM(qs.total_worker_time) AS total_cpu_time,�
              
    SUM(qs.total_elapsed_time) AS total_duration_time,�
              
    SUM(qs.execution_count) AS total_execution_count,
              
    SUM(qs.total_worker_time) / SUM(qs.execution_count) AS AvgCPUTime,
              
    COUNT(*) AS  number_of_statements,�
              
    qs.plan_handle , db.name
          
    FROM�
              
    sys.dm_exec_query_stats qs
              
    CROSS apply sys.dm_exec_sql_text(sql_handle) AS sql_text
          
    LEFT OUTER JOIN sys.databases db
            
    ON sql_text.dbid = db.database_id
          
    --WHERE dbid = 10
          
    GROUP BY sql_text.TEXT,
          
    qs.plan_handle , db.name
    )a
    ORDER BY AvgCPUTime DESC
  9. Comparing which way is better.  To compare how long and how much data was needed to satisfy two different queries you can just click on the Include Client Statistics button before you run the first query and it will start capturing the statistics for you:
    image
  10. And finally the built-in reports.  To run any of them just Right-Click any database in SSMS Object Explorer and navigate to the report that you want:

That pretty much wraps it up for what we covered yesterday.  I will put some examples together for the Common Table Expressions (CTE), RANK, DENSE_RANK, and NTILE fuctions that I mentioned yesterday so that we can go over them at the next one.  Next Tuesday work good for you?  :-)
If you would like anything else covered you can just email me or comment here.

SSAS Server Cant See Its Own Cubes in SSMS

I’ve got an oddball situation going on here (I know what you’re thinking: Par for the course).  I’ve built out a pair of new Windows Server 2008 R2 \ SQL Server 2008 SP1 CU5 machines.  Both are running great and returning data faster than anything we’ve ever seen before except for one small problem:  One of the servers can’t see it’s own cubes.  The cubes are there and everything.  I can connect to them with BIDS to deploy updates, SSMS to process them, and I can even query the cubes and get results back in Excel.  The server itself just can’t see them.

Here’s what it looks like if you’re logged into the machine directly:

LocalConnection  

And then here’s what it looks like if you connect to that same server from my desktop or any other server:

RemoteConnection

Another weird thing is that the other server that was built out the same way at the same time can see it’s own cubes just fine.  It’s just this one server that can’t see it’s own cubes.

I’ve only heard of one other person who has seen this behavior so the whole point of this blog post is just to see if anyone else is running into this issue.  If so please comment and we can get a connect issue filed if it’s prevalent enough reproduceible.

* Please Note: The names have been changed  to protect the innocent servers under my corrupting influence control.

**  Please take a look at the comments below:
***  As a work-around you can Right-Click on the SSMS icon and select > Run as Administrator to get SSMS to see it’s own cubes:  “If you skip step in the setup where it asked you to add current user to AS server admin role, then you would need to run SSMS as administrator.”