Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Your profile

Search

July 2009
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    

XML Feeds

Authors

All the LessThanDot Journals

Automatically create a SQL Server table in a new database.

by George Mastros


Permalink 03 Jul 2009 10:53 , Categories: Data Modelling & Design, Microsoft SQL Server Admin, Microsoft SQL Server

I've seen this question numerous times in the forums I like to frequent. The idea is, when you create a new database, you may want that database to have several tables, some of which are automatically populated with data (thinking about relatively static lookup tables here).

The process mentioned here may not be useful for everyone, but it is certainly something to consider.

There is a system database named Model. This database is used when you create a new user database. In fact, any object (table, view, stored procedures, functions, etc…) that exists in the model database will be copied to your newly created database. This may be a blessing and a curse, so use this suggestion wisely. If you have a SQL Instance where you need to set up a new database for each customer, and that is all the instance is used for, then it makes sense to create your objects in the Model database. However, if you have a general purpose instance that you are using for various databases, you probably won’t want to put your objects in the Model database.

Enough of the chatter, let's see how this can be done.

First, create a table in the Model database.

  1. USE Model
  2. go
  3.  
  4. CREATE TABLE TestAutoDBCreation(Id INT, Color VARCHAR(20))
  5. INSERT INTO TestAutoDBCreation VALUES(1, 'Red')
  6. INSERT INTO TestAutoDBCreation VALUES(2, 'Blue')

Now, let’s create a new database.

  1. USE Master
  2. go
  3. CREATE DATABASE NewDatabaseWithModelTable

Now, let's make sure the table (and it's data) exist in the new database.

  1. USE NewDatabaseWithModelTable
  2. go
  3. SELECT * FROM TestAutoDBCreation

As you can see, the table that was created in Model exists in the newly created database. It even has all the data that was loaded in to it.

Now, let’s clean up after ourselves:

  1. USE Model
  2. go
  3. DROP TABLE TestAutoDBCreation
  4. go
  5. USE Master
  6. go
  7. DROP DATABASE NewDatabaseWithModelTable
2 comments »Send a trackback » 65 views

Trust

by chopstik


Permalink 02 Jul 2009 08:44 , Categories: Ethics & IT

Recently, I had a conversation with a friend and former co-worker. He's essentially been running a one-man shop since I left there but the company had recently hired a new developer who claimed to be very experienced in the technologies to which the office is trying to migrate (notably .NET). My friend had been tasked with bringing the new employee up-to-speed and working with the current projects. However, there have apparently been some concerns that the new employee may not have the abilities he claimed in his interview (because it is a small shop, there was no formal technical interview) and that the new employee may not have the necessary soft skills to fit in with his co-workers. My friend asked for my opinion on the situation (since I worked there previously). Apparently, his concern was on how far he should trust the new employee in terms of working on various applications.

I had to stop and think for a little bit because I had never previously considered how others may do things nor on the trust level needed to work with others. I should caveat my commentary here by stating that, up until my current position, I had worked mainly as a cowboy developer in small one or two-man shops. When I had to work with others, there was an implicit level of trust and communication because that is how I deal with everyone. Until you prove to me that you cannot be trusted, I expect that you will do what you say.

That being said, I considered the idea of trust in an IT shop. Everyone has heard stories of developers who work to ensure job security by keeping all information to themselves - even to the detriment of the company as a whole. I do not subscribe to that theory. When my friend was first hired at my previous employer, it was my responsibility to bring him up to speed and to ensure he could do the work. From the outset, I worked to communicate with him constantly on various projects so that, if I were to be hit by a bus, at least someone would know what was happening and could continue. While I am not great at documenting my code, I tried to ensure that the code was at least documented to the point that a beginning developer could read it and have a good idea of what it did. And I made myself available for questions at any time and tried not to show any exasperation if the questions seemed - for lack of a better word - stupid. After all, there is no such thing as a stupid question, just stupid people. And stupid people don't ask questions.

I checked up on my friend's work until I was comfortable with his level of knowledge and understanding that he could do the work independently. As I sensed that he was ready to move up or move on, I allowed him to work on larger or more complicated projects. When I left the company about 2 years after his arrival, I was comfortable that he could take over my responsibilities without any significant performance hits to the department - and made my boss aware that, while she may miss my contributions, my friend was more than able to take them over. Could he do everything I could in the same time frame? No, but that did not mean he could not do it at all. But the key point is that he was able to grow and develop on his own. I learned that mentoring new people was an important aspect of IT as it forced me to understand the process well enough to be able to explain it someone else.

And none of that would have happened without a level of trust. Trust on my part that he could do the job he said he could when he was interviewed. Trust on his part that I would make him not only a part of the team but that I would help him to continue to learn and develop. Trust is not an easy thing to have and it is far too easily broken, but without it, the IT world would not be where it is today.

After all, open-source technology is probably a direct result of trust...

1 comment »Send a trackback » 231 views

Reading from a HD that was formatted with ext3 from Windows Vista

by chrissie1


Permalink 02 Jul 2009 07:39 , Categories: Operating Systems Tags: ext3, read, windows

Yesterday my nas died on me, actualy it didn't they I just couldn't connect to it anymore and this thing didn't have a USB port only ethernet.

So I decided to get the disk out and mount it in my desktop. SInce it was Sata that was easy. But I hit a little snag and that is that it was formatted in ext3 and windows does not read ext3

So I googled and found Linux reader 1.1 from diskinternals you find it in the freeware section. Yes freeware. It's very small and it installs in seconds.

You then get a screen with your drives on it, ext 3 drives included.

You then choose the folder you want to recover and click on recover this folder in the sidebar.
After which it starts.

And now I have one extra 250GB drive in my desktop.

And like Ted says, Backups are for sissies.

Leave a comment »Send a trackback » 58 views

The use of descriptive variable names is forbidden

by chrissie1


Permalink 01 Jul 2009 23:18 , Categories: Microsoft Technologies, VB.NET Tags: vb.net

Still legacy application

  1. For x = 1 To y
  2.   q(x, y + 1) = q(x, y + 1) + p(I, J) * ay(I)
  3.   For z = 1 To y
  4.     q(z, x) = q(z, x) + p(I, z) * p(I, x)
  5.   Next z
  6. Next x

I immediatly refactored the I and J to be lowercase.

Leave a comment »Send a trackback » 114 views

Dynamic column names and fields in SSRS (Custom Matrix)

by onpnt


Permalink 01 Jul 2009 12:26 , Categories: Data Modelling & Design, Database Programming, Database Administration, Microsoft SQL Server Admin, Microsoft SQL Server

I had no choice but to do work with creating dynamic column headings and dynamically determine what field in my dataset should go where in a report today. Sense this is the second time I’ve gone through this exercise and knowing the lack of information out there on really how to do it, I thought it deserves a blog entry.

So here is the basis of the requirements. You have a query that uses PIVOT but thrown into the mix is the need for dynamic columns in the PIVOT. This is usually a task when you are going after things like current week plus the last 52 weeks. That was the case in this situation. I needed to bring in a dynamic set of columns to be used in PIVOT. The matrix in 2005 did not give me what I needed in the end result so this is the path I took.

First task is to write the procedure to use PIVOT with dynamic column headers. I’m not going to go into that method sense it’s well documented out there and out of scope. I will point you to Pivots with Dynamic Columns in SQL Server 2005 as it explains the way to accomplish this well.

I wrote something in AdventureWorks to for this example so if you have AdventureWorks floating around you should be able to read this and run through step for step with success.

Here is our procedure. I’m sure my methods will take great notice from my local TSQL friends :) The dynamic SQL more so than anything...

  1. CREATE PROCEDURE GetSalesPerWeek
  2. AS
  3. DECLARE @weeks_ordered TABLE (num VARCHAR(3))
  4. DECLARE @weeks TABLE (wk INT)
  5. DECLARE @DATE DATETIME
  6. DECLARE @cols NVARCHAR(3000)
  7. DECLARE @INT INT
  8. DECLARE @col_pv VARCHAR(2000)
  9. DECLARE @query VARCHAR(3000)
  10.  
  11.  
  12. SET @INT = 1
  13. SET @DATE = GETDATE()
  14.  
  15. WHILE @INT <= 52
  16. BEGIN
  17.     INSERT INTO @weeks VALUES (@INT)
  18.     SET @INT = @INT + 1
  19. END
  20.  
  21.  
  22. INSERT INTO @weeks_ordered
  23. SELECT
  24. wk
  25. FROM @weeks
  26. ORDER BY
  27. CASE WHEN DATEPART(wk,@DATE) - wk < 0
  28. THEN DATEPART(wk,@DATE) - wk + 53
  29. ELSE DATEPART(wk,@DATE) - wk
  30. END DESC
  31.  
  32. SELECT @col_pv = STUFF(( SELECT  
  33.                                 '],[' + w.num
  34.                         FROM  @weeks_ordered AS w
  35.                         FOR XML PATH('')
  36.                       ), 1, 2, '') + ']'
  37.  
  38. SELECT  @cols = STUFF(( SELECT  
  39.                                 '],0) as W' + CASE WHEN CAST(w.num - 1 AS VARCHAR(2)) = 0 THEN '52' ELSE
  40.                                                         CAST(w.num - 1 AS VARCHAR(2)) END + ',isnull([' + w.num
  41.                         FROM  @weeks_ordered AS w
  42.                         FOR XML PATH('')
  43.                       ), 1, 2, '') + '],0) as W' + CAST(DATEPART(wk,GETDATE()) AS VARCHAR(2))
  44.  
  45.  
  46. IF OBJECT_ID('tempdb.dbo.#detail') IS not null
  47.         DROP TABLE #detail
  48.  
  49. CREATE TABLE #detail
  50. (
  51. AccountNumber VARCHAR(10)
  52. ,PruductNumber VARCHAR(25)
  53. ,OrderQty INT
  54. ,WeekNumber SMALLINT
  55. )
  56.  
  57.  
  58. INSERT INTO #detail
  59. SELECT
  60.     cust.AccountNumber
  61.     ,items.ProductNumber
  62.     ,det.OrderQty
  63.     ,DATEPART(wk,hdr.ShipDate) WeekNumber
  64. FROM
  65. Sales.SalesOrderHeader hdr
  66. INNER Join Sales.SalesOrderDetail det ON hdr.SalesOrderID = det.SalesOrderID
  67. INNER Join Production.Product items ON det.ProductID = items.ProductID
  68. INNER Join Sales.Customer cust ON hdr.CustomerID = cust.CustomerID
  69. INNER Join @weeks ord ON DATEPART(wk,ShipDate) = wk
  70. WHERE ShipDate >= DATEADD(wk,-52,'2004-06-01')
  71. GROUP BY
  72.     cust.AccountNumber
  73.     ,items.ProductNumber
  74.     ,det.OrderQty
  75.     ,DATEPART(wk,hdr.ShipDate)
  76.     ,wk
  77. ORDER BY
  78. CASE WHEN DATEPART(wk,ShipDate) - wk < 0
  79. THEN DATEPART(wk,ShipDate) - wk + 53
  80. ELSE DATEPART(wk,ShipDate) - wk
  81. END
  82.  
  83.  
  84. SET @query =
  85. '
  86. Select 
  87.     AccountNumber
  88.     ,PruductNumber
  89.     , '     + RIGHT(@cols,LEN(@cols)-10) + '
  90. From
  91.     #detail as sales
  92. PIVOT (sum(OrderQty) FOR WeekNumber IN (' + @col_pv + ')) as pv
  93. Order By AccountNumber
  94. '
  95. EXEC(@query)


The results shows us the PIVOT results of each account number and the sales for the week of the year

The problem with all of this is the dynamic nature of the column names. In reporting services we’re used to handling column names as static entities. So here is how we’ll build our report given the fact these column names can and will change over time.

So create a new report in your solution and add a new DataSet. Make it a text call with the following statement

  1. EXEC GetSalesPerWeek

Run the DataSet to verify everything comes in ok.

Now add a new table to your empty report. Add the account number and product number as you would normally. Next we need to figure out what week is actually first. To do this we’re going to write a function in the code section of SSRS

In the layout tab go to Report and select Report Properties. This will give you the properties for the entire report. Select the Code tab. Copy and paste the following code into the window

  1. Public Function GetColumnHeading(ByVal x As Integer)
  2.        Dim WeeksArr As New System.Collections.ArrayList()
  3.         Dim i As Long
  4.         Dim CurrentWeek As Long
  5.  
  6.         CurrentWeek = DatePart(DateInterval.WeekOfYear, System.DateTime.Now)
  7.  
  8.         For i = 1 To 52
  9.             WeeksArr.Add(1 + (i + CurrentWeek - 1) Mod 52)
  10.         Next
  11.         Return WeeksArr(x)
  12.     End Function

This code was written by our own gmmastros. Thanks to him for this and the help it gave me when I needed it. Gets the job done and it does it quickly.

Final results should look like this

Hit OK to save.

Now in the field next to the Product Number go ahead and enter an expression for the heading like this

="W" & Code.GetColumnHeading(0)

Recall in our procedure we return each week as Wnn for the week number. So in our code we created an ArrayList filled up with the order we want. The same order we based the procedure off of. Now by using the index of the ArrayList we can simply call for the heading that should be all the way to the left (-51 weeks from the current) by means of index of 0. In the details textbox we can then simply do the following as well given the same guidelines

=Fields("W" & Code.GetColumnHeading(0)).Value

Most developers don’t know they can reference the fields by name in this manner. Usually it just isn’t required and that is the case. It can be useful to note that you can dynamically fill the object name in though and get the same results as Fields!name.Value

I went ahead and put a few more columns and increased the index requested from the ArrayList. Running that results in the following.

Now you have your customer matrix in a sense by means of dynamic column and field referencing. You also a nice example of PIVOT by means of dynamic column names.

This blog probably has about 12 pages worth of explanations but I’d like to leave those to the forums so please follow the directions below if you want to discuss this method further. Otherwise, have fun with it!




*** If you have a SQL related question try our Microsoft SQL Server Programming forum or our Microsoft SQL Server Admin forum

3 comments »Send a trackback » 344 views

:: Next >>