Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Your profile

Search

November 2008
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

XML Feeds

Tags: sql

All the LessThanDot Journals

How To Convert IP Addresses Between Bigint and Varchar

by SQLDenis


Permalink 05 Oct 2008 12:06 , Categories: Data Modelling & Design Tags: how to, sql, sql server 2008, tip

Before we start with code let us take a sample IP address, does 127.0.0.1 look familiar? Yes that is your local IP address.

Here it is in decimal and binary
127 0 0 1
01111111 00000000 00000000 00000001

Now to convert, you would take the first value,
add the second value + 256
add the third value + (256 * 256) = 65536
add the fourth value + (256 * 256 * 256) =16777216

So in our case the select would be

  1. SELECT
  2. 1 +
  3. 0 * 256 +
  4. 0 * 65536 +
  5. 127 * 16777216

which is
2130706433

So to convert from IP Adress to integer is very simple, you use PARSENAME to split it up and do the math. Here is the function.

  1. CREATE FUNCTION dbo.IPAddressToInteger (@IP AS VARCHAR(15))
  2. RETURNS BIGINT
  3. AS
  4. BEGIN
  5.  RETURN (CONVERT(BIGINT, PARSENAME(@IP,1)) +
  6.          CONVERT(BIGINT, PARSENAME(@IP,2)) * 256 +
  7.          CONVERT(BIGINT, PARSENAME(@IP,3)) * 65536 +
  8.          CONVERT(BIGINT, PARSENAME(@IP,4)) * 16777216)
  9.  
  10. END
  11. GO

But how do you get 127.0.0.1 out of 2130706433?
It is the reversed of what we did before (surprise) so instead of multiplying we will be dividing
Here is the funcion

  1. CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS BIGINT)
  2. RETURNS VARCHAR(15)
  3. AS
  4. BEGIN
  5.  DECLARE @Octet1 TINYINT
  6.  DECLARE @Octet2 TINYINT
  7.  DECLARE @Octet3 TINYINT
  8.  DECLARE @Octet4 TINYINT
  9.  DECLARE @RestOfIP BIGINT
  10.  
  11.  SET @Octet1 = @IP / 16777216
  12.  SET @RestOfIP = @IP - (@Octet1 * 16777216)
  13.  SET @Octet2 = @RestOfIP / 65536
  14.  SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)
  15.  SET @Octet3 = @RestOfIP / 256
  16.  SET @Octet4 = @RestOfIP - (@Octet3 * 256)
  17.  
  18.  RETURN(CONVERT(VARCHAR, @Octet1) + ‘.’ +
  19.         CONVERT(VARCHAR, @Octet2) + ‘.’ +
  20.         CONVERT(VARCHAR, @Octet3) + ‘.’ +
  21.         CONVERT(VARCHAR, @Octet4))
  22. END

Now let’s try this out, first run this

  1. SELECT dbo.IPAddressToInteger(‘127.0.0.1′)

That returns 2130706433
Now run this

  1. SELECT dbo.IntegerToIPAddress(2130706433)

That returns 127.0.0.1

Thanks to K. Brian Kelley for the inspiration for this post, you can also check http://www.truthsolutions.com/ to see some of his books

And also check out the related Order IP Addresses wiki article which I wrote a while ago

2 comments »Send a trackback » 510 views

SQL Server 2008 Cumulative Update 1 is available from Microsoft

by SQLDenis


Permalink 23 Sep 2008 05:49 , Categories: Data Modelling & Design Tags: cumulative update, hotfix, sql, sql server 2008

Cumulative Update 1 contains hotfixes for the Microsoft SQL Server 2008 issues that have been fixed since the release of SQL Server 2008.

You can request this SQL Server 2008 Cumulative Update here: http://support.microsoft.com/default.aspx/kb/956717

Below is the long list of things that have been fixed

When you use a SAP client computer to view a SQL Server database, the database may be smaller than expected/kbIn SQL Server 2008, a query returns incorrect results for the Date data type when you run the query on a partitioned table that uses data compression on only one of the partitions

A mirror server cannot fail over to a principal server in a SQL Server 2008 failover cluster

You receive an error message that states that the broker GUIDs do not match when you try to establish database mirroring in SQL Server 2008 or in SQL Server 2005

An XML query that contains the @Table variable or the @XML variable takes a long time to complete in SQL Server 2008

When you query through a view that uses the ORDER BY clause in SQL Server 2008, the result is still returned in random order

The result for the Sum or Count function returns an empty value when you query a SQL Server 2008 Analysis Services cube

Some lists that use visibility toggles may not work as expected when you upgrade to SQL Server 2008 Reporting Services

Some text characters are displayed as square glyphs in a report that you design or view by using SQL Server 2008 Reporting Services

Error message when you try to run or preview a very large report in Microsoft SQL Server 2008 Reporting Services: “Exception of type System.OutOfMemoryException was thrown”

Error message when you try to view a report in SQL Server 2008 Reporting Services: “Object reference not set to an instance of an object. (rsRuntimeErrorInExpression)”

SQL Server 2008 Reporting Services stops responding when you try to render a report in the Image format

When you try to run a report that has recursive hierarchy and that uses toggles in the hierarchy, you may receive unpredictable results in SQL Server 2008 Reporting Services

A dump file may be generated in the Reporting Services Logfiles folder and you may receive an error message when you try to render a report in SQL Server 2008 Reporting Services

The Gauge report item uses only one point after you add multiple points to the item in SQL Server 2008 Reporting Services

Some items are split over two pages when you export a report to a PDF in SQL Server 2008 Reporting Services and you set the KeepTogether property

The embedded Tablix row and column size is not 100% for cells that contain data when a Tablix is embedded inside another Tablix in SQL Server 2008 Reporting Services

An image that is nested in a Tablix cell in SQL Server 2008 Reporting Services is displayed incorrectly when the Sizing property of the image is set to AutoSize

Images in rows are not displayed correctly for static Tablix members in a SQL Server 2008 Reporting Services report

You receive an error message when you use the LoadReportDefinition API to view a drillthrough report or a subreport report in Report Builder in SQL Server 2008 Reporting Services

SQL Server 2008 Reporting Services interprets the Slant property as a positive slope

SQL Server 2008 Reporting Services may stop responding when you move a history snapshot or a linked report to a new folder location

Error message when you try to create a query against a Hyperion Essbase cube database: “OLAP error (1260046): Unknown Member PARENT_UNIQUE_NAME used in query”

Error message when you run an MDX query that uses the CREATE GLOBAL CUBE statement to create a local cube in SQL Server 2008 Analysis Services or in SQL Server 2005 Analysis Services: “The syntax for ‘<MDXFunctionName>’ is incorrect”

The SQL Server 2005 Distribution Agent and the SQL Server 2008 Distribution Agent do not skip error 20598 when you configure a SQL Server 2000 transactional publication to skip error 20598

In SQL Server 2008 or in SQL Server 2005, the session that runs the TRUNCATE TABLE statement may stop responding, and you cannot end the session

You cannot edit a component that has multiple inputs in a SQL Server 2008 or SQL Server 2005 Integration Services package

An incorrect aggregate value is returned when you run an MDX query against a parent/child dimension that has the HideMemberIf property set to ParentIsBlankSelfOrMissing in SQL Server 2008 or in SQL Server 2005

Error message when you run an INSERT statement in SQL Server: “Cannot insert an explicit value into a timestamp column”

You cannot view calculated members in an Excel 2007 pivot table that references an OLAP table in SQL Server 2005 Analysis Services Service Pack 2 or in SQL Server 2008 Analysis Services

Error message when you run an MDX query in SQL Server 2008 Analysis Services: “The MDX function failed because the coordinate for the ‘<AttributeName>’ attribute contains a set”

Error message when you update a table at the subscriber in a transactional replication in SQL Server 2005: “Updateable Subscriptions: Rows do not match between Publisher and Subscriber”

No rows are returned when you use the sp_replqueuemonitor stored procedure to list the queued messages for a queue-updating subscription in SQL Server

When you update rows by using a cursor in SQL Server 2005, the update may take a long time to finish

Error message when you process a partition from SQL Server 2005 Analysis Services Cumulative Update 7: “Detected inconsistency between User define slice and detected slice of partition. The slice specified for the %{Property/} attribute is incorrect”

You receive a “Current session is no longer valid” error message or an access violation occurs when you process a cube in SQL Server 2008 Analysis Services

Error message when you run an UPDATE statement against a table that has a DML trigger in SQL Server 2008: “An inconsistency was detected during an internal operation”

Analysis Services may stop responding when a NonEmpty clause causes many cell errors

A SQL Server 2008 Analysis Services server may stop responding when you try to run an MDX query that uses cell security
50003352 957820 (http://support.microsoft.com/kb/957820/) FIX: The mining model opens a blank task editor window when you try to deploy the Data Mining Model Training task in a SQL Server 2008 Integration Services project in Business Intelligence Development Studio

You cannot merge a publication that has spatial types that include large values with a SQL Server CE subscriber

A MERGE statement may not enforce a foreign key constraint when the statement updates a unique key column that is not part of a clustering key and there is a single row as the update source in SQL Server 2008

The IntelliSense feature does not work correctly for a database that uses the Turkish collation and that uses the case-insensitive collation sort order in SQL Server 2008

A NullReferenceException error for T-SQL Debugger occurs when you use the SET SHOWPLAN_XML ON option in a Transact-SQL statement on a instance of SQL Server 2008

The IntelliSense feature incorrectly completes the logical operators in the CASE WHEN clause in SQL Server 2008

You receive an error message when you click the View Single Column Profile By Column button in the Data Profile Viewer in SQL Server 2008: “Unhandled Exception”

The IntelliSense feature stops working when you type a query that has a specific lexical combination in SQL Server Management Studio in SQL Server 2008

You cannot start the Data Profile Viewer (DataProfileViewer.exe) in SQL Server 2008

In SQL Server 2008, the IntelliSense feature may become unavailable when you type Transact-SQL statements in the Query Editor in SQL Server Management Studio

Error message when you start the SQL Server 2008 Reporting Services Configuration Manager: “Invalid namespace”

The SimSun font is not displayed correctly when you view a SQL Server 2008 Report Services report

Clients cannot connect to the Report Server Web service in SQL Server 2008 Reporting Services

Error message when you render a report in SQL Server 2008 Reporting Services: “A generic error occurred in GDI+”

Data disappears from a report that contains an inner group that is set to an initial state of “Hidden” in SQL Server 2008 Reporting Services

A SQL Server 2008 Reporting Services report may repaginate continually and consume 100% of CPU resources

No records may be returned when you call the SQLExecute function to execute a prepared statement and you use the SQL Native Client ODBC Driver in SQL Server 2008

Error message when you install SQL Server 2008 Express edition on a domain controller that is running Windows Server 2003 SP2 or Windows Small Business Server 2003 SP1: “Exception has been thrown by the target of invocation”

You cannot upgrade a non-English instance of SQL Server 2000 Reporting Services to SQL Server 2008 Reporting Services

When you try to run SQL Server 2008 database engine repair from a DVD, the repair fails, and you may receive error messages

When you install SQL Server 2008, the installation fails, and the “Attributes do not match” error message is logged in the Summary.txt file

SQL Server Setup does not use the instance name that you provide in the modified Config.ini file when you try to install SQL Server 2008 Express

Data warehousing may stop collecting data when many time-outs occur

You receive a memory error message when you try to run SQL Server Setup from a network resource

You may not be able to uninstall a prepared instance of SQL Server 2008

Cluster upgrade to SQL Server 2008 fails when SQL Server 2005 cluster nodes have different installed features

When you install a clustered instance of SQL Server 2008, account validation fails even though you have specified the correct domain account and password

The CompleteFailoverCluster action does not detect the correct SKU that is prepared by using the PrepareFailoverCluster action in SQL Server 2008

Error message when you try to add a second node to a SQL Server 2008 failover cluster: “The current SKU is invalid”

You receive an error message that the file is being used by another process when you try to rename or move an output file from a job in SQL Server Agent in SQL Server 2008

A new node is not added to a SQL Server 2008 Analysis Services cluster or a SQL Server 2008 Reporting Services cluster if the SQL Server 2008 Database Engine is not installed

Event ID 7904 is logged, and the SQL Server 2008 database is corrupted when you restore a SQL Server 2008 database from a sequence of transaction log backups

When you programmatically retrieve data from a SQL Server 2008 database, the data in memory may be overwritten

The Service Broker connections between endpoints may experience a deadlock condition when the intiator queues contain many messages

The clustered index table may take longer than you expect to be rebuilt when you use the ALTER INDEX REBUILD statement in SQL Server 2008

A SQL Server 2008 query returns incorrect results when you create a spatial index in a table that contains a composite primary key

The Database Mirroring feature does not work on a SQL Server 2008-based mirror server when you perform a rolling upgrade on the mirror server

Extended Events session produces an empty value for data captured for certain actions

The Processes pane in the Activity Monitor incorrectly shows sessions as head blockers in SQL Server 2008

When a SQL Server 2008 policy file executes a WMI query, the policy always executes the query against the local server regardless of the intended target

You cannot expand the Facets node under the Policy Management node in SQL Server Management Studio in a non-English version of SQL Server 2008

1 comment »Send a trackback » 1906 views

Find Out The Recovery Model For Your Database

by SQLDenis


Permalink 30 Aug 2008 08:18 , Categories: Data Modelling & Design Tags: administration, database, sql, sql server

You want to quickly find out what the recovery model is for your database but you don’t want to start clicking and right-clicking in SSMS/Enterprise Manager to get that information. This is what you can do, you can use databasepropertyex to get that info. Replace ‘msdb’ with your database name

  1. SELECT DATABASEPROPERTYEX(‘msdb’,‘Recovery’)

What if you want it for all databases in one shot? No problem here is how, this will work on SQL Server version 2000

  1. SELECT name,DATABASEPROPERTYEX(name,‘Recovery’)
  2.  FROM sysdatabases

For SQL Server 2005 and up, you should use the following command

  1. SELECT name,recovery_model_desc
  2. FROM sys.databases

I have also added this to our SQL Server admin Wiki here: Find Out The Recovery Model For Your Database
Make sure to check out the other wiki entries

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

Leave a comment »Send a trackback » 736 views

SQL Server 2008 Express with Advanced Services And SQL Server 2008 Express With Tools Now Available For Download

by SQLDenis


Permalink 26 Aug 2008 12:25 , Categories: Data Modelling & Design Tags: free, rdmbs, sql, sql server 2008, sql server 2008 express, t-sql

There are 3 versions of SQL Server 2008 Express now available for download from the SQL Server 2008 Express site. Below are the 3 different versions

SQL Server 2008 Express

  • SQL Server database engine - create, store, update and retrieve your data

SQL Server 2008 Express with Tools

  • SQL Server database engine - create, store, update and retrieve your data
  • SQL Server Management Studio Basic - visual database management tool for creating, editing and managing databases

SQL Server 2008 Express with Advanced Services

  • SQL Server database engine - create, store, update and retrieve your data
  • SQL Server Management Studio Basic - visual database management tool for creating, editing and managing databases
  • Full-text Search - powerful, high-speed engine for searching text-intensive data
  • Reporting Services - integrated report creation and design environment to create reports

Get it all here http://www.microsoft.com/express/sql/download/

Make sure to register your copy so that you can get a free eBook and other goodies

1 comment »Send a trackback » 515 views

Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code

by SQLDenis


Permalink 17 Aug 2008 07:55 , Categories: Data Modelling & Design Tags: database, dates, indexing, performance tuning, rdbms, sql, t-sql, temporal data

Take a look at this query.

  1. SELECT * FROM
  2.  
  3. (
  4.  
  5. SELECT customer_id, ‘MTD’ AS record_type, COUNT(*), SUM(), AVG()
  6.  
  7. FROM payment_table
  8.  
  9.  
  10. WHERE YEAR(payment_dt) = YEAR(GETDATE())
  11.  
  12. and MONTH(payment_dt) = MONTH(GETDATE())
  13.  
  14. GROUP BY customer_id) MTD_payments
  15.  
  16. UNION ALL
  17.  
  18. (
  19.  
  20. SELECT customer_id, ‘YTD’ AS record_type, COUNT(*), SUM(), AVG()
  21.  
  22. FROM payment_table
  23.  
  24. WHERE
  25.  
  26. WHERE YEAR(payment_dt) = YEAR(GETDATE())
  27.  
  28. GROUP BY customer_id) YTD_payments
  29.  
  30. UNION ALL
  31.  
  32. (
  33.  
  34. SELECT customer_id, ‘LTD’ AS record_type, COUNT(*), SUM(), AVG()
  35.  
  36. FROM payment_table) LTD_payments
  37.  
  38. ) payments_report
  39.  
  40. ORDER BY customer_id, record_type

Can you see the problem?
A person had this query, it would run for over 24 hours. Wow, that is pretty bad, I don’t think I had ever written something that ran over an hour, and the ones I did were mostly defragmentation and update statistics jobs.

The problem is that the following piece of code

  1. WHERE YEAR(payment_dt) = YEAR(GETDATE())
  2. and MONTH(payment_dt) = MONTH(GETDATE())

is not sargable. First what does it mean to be sargable? A query is said to be sargable if the DBMS engine can take advantage of an index to speed up the execution of the query (using index seeks, not covering indexes). The term is derived from a contraction of Search ARGument Able.

This query is not sargable because there is a function on the column, whenever you use a function on the column you will not get an index seek but an index scan. The difference between an index seek and an index scan can be explained like this: when searching for something in a book, you go to the index in the back find the page number and go to the page, that is an index seek. When looking for something in a book you go from page one until the last page, read all the words on all the ages and get what you need, that was an index scan. Do you see how much more expensive in terms of performance that was?

Let’s get back to the query, what can we do to make this piece of code use an index seek?

  1. WHERE YEAR(payment_dt) = YEAR(GETDATE())
  2. and MONTH(payment_dt) = MONTH(GETDATE())

You would change it to this:

  1. WHERE payment_dt >= DATEADD(mm, DATEDIFF(mm, 0, GETDATE())+0, 0)
  2. and payment_dt < DATEADD(mm, DATEDIFF(mm, 0, GETDATE())+1, 0)

You can see the complete question on the MSDN forum site here:
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3746751&SiteID=1

The Person said that his query went from over 24 hours to 36 seconds. Wow!! That is very significant. hardware cannot help you out if you have bad queries like that.

The same exact day I answered a very similar question, take a look here: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3752248&SiteID=1

The person had this

  1. AND DATEDIFF(d, ‘08/10/2008′, DateCreated) >= 0
  2. AND DATEDIFF(d, DateCreated, ‘08/15/2008′) >= 0

I told him to change it to this

  1. AND DateCreated >= ‘08/10/2008′
  2. and DateCreated <= ‘08/15/2008′

And that solved that query. If you are interested in some more performance, I have written some Query Optimization items on the LessThanDot Wiki. Below are some direct links

Case Sensitive Search
No Functions on Left Side of Operator
Query Optimizations With Dates
Optimization: Set Nocount On
No Math In Where Clause
Don't Use (select *), but List Columns

If you are interested in some blogposts about dates, take a look at these two which I wrote earlier
How Are Dates Stored In SQL Server?
Do You Know How Between Works With Dates?

16 comments »1 trackback » 5850 views

:: Next >>