Tuesday, November 29, 2005

SQL Server 2000 Undocumented Procedures For Files, Drives and Directories

Below are some undocumented SQL Server 2000 procedures for information about files, drives and directories.
You should not depend on this because they might me deprecated in the future, but if you want to find out fast if a file exists, what the size is and other things I think that they are good to use since it saves you some scripting or using terminal services

returns the network name of the server

Returns 1 if a file exists, 1 if the file is a directory and 1 if a parent directory exists
master..xp_fileexist 'C:\Program Files\Microsoft SQL Server\MSSQL\readme.txt'

Lists all the subdirecories of a given path including the level of the path
master..xp_dirtree 'C:\Program Files\Microsoft SQL Server\MSSQL\'

Lists a directory's immediate sub directory (1 level down)
master..xp_subdirs 'C:\Program Files\Microsoft SQL Server\MSSQL\'

List the file detals for a file, the following fields are returned
Alternate Name,Size,Creation Date, Creation, Time Last Written, Date Last Written, Time Last Accessed,
Date Last Accessed Time and Attributes
master..xp_getfiledetails 'C:\Program Files\Microsoft SQL Server\MSSQL\readme.txt'

List all the fixed drives and free MB on the machine

Returns the database name, size and space used for the temp db

Lists all the ODBC datasources (name and description) available on the machine

List the current error logs (Archive #, Date and Log File Size) on the server

Wednesday, November 23, 2005

Calculating Thanksgiving By Using SQL in SQL Server

Happy Thanksgiving, here is some SQL code to calculate the next 11 (including today) Thanksgiving days


DECLARE @intLoopCounter INT
SELECT @intLoopCounter =0

SELECT @dtmStardate ='2005-11-24 00:00:00.000'

SELECT @dtmEnddate ='2015-11-30 00:00:00.000'

WHILE @intLoopCounter <(SELECT DATEDIFF(d,@dtmStardate,@dtmEnddate))
INSERT INTO #NumberPivot
VALUES (@intLoopCounter)
--+ 7 will only work if you start from a Thursday, use +1 for other days
SELECT @intLoopCounter = @intLoopCounter +7

--One way

THEN MAX((DATEADD(d,number,@dtmStardate)))
ELSE MAX((DATEADD(d,number,@dtmStardate))) -7 END AS ThanksGivingDay,
DATEPART(yyyy,DATEADD(d,number,@dtmStardate)) AS [Year]
FROM dbo.#NumberPivot
WHERE DATEPART(mm,DATEADD(d,number,@dtmStardate)) = 11
GROUP BY DATEPART(mm,DATEADD(d,number,@dtmStardate)) ,DATEPART(yyyy,DATEADD(d,number,@dtmStardate))

--And another
SELECT dt AS ThanksGivingDay, YEAR(dt) AS [Year]
( SELECT DATEADD(d,number,@dtmStardate) AS dt
FROM dbo.#NumberPivot
) X

--Enjoy the turkey

Tuesday, November 22, 2005

SQL Server Podcast With Dr Jim Gray

SQL Down Under has announced their latest podcast with A.C.M. Turing Award winner and Microsoft Distinguished engineer Dr Jim Gray discussing the Future of SQL Server.
In this show, Jim (a database industry legend) gives his thoughts on the future directions for database products, LINQ, T-SQL and discusses his interests in spatial data.
Get the podcast from SQL Down Under

Monday, November 21, 2005

SQL Server 2005 Virtual Labs

There are virtual labs available for SQL Server 2005
You get a downloadable manual and a 90-minute block of time for each module. You can sign up for additional 90-minute blocks at any time.
Go here to access the following labs

SQL Server 2005 Integration Services
SQL Server 2005 Reporting Services
SQL Server 2005 Introduction to SQL Server Management Studio
SQL Server 2005 XML Capabilities
SQL Server 2005 SQL Server and ADO.NET (Lab A)
SQL Server 2005 SQL Server and ADO.NET (Lab B)
SQL Server 2005 T-SQL Enhancements
SQL Server 2005 Server Management Objects
SQL Server 2005 Web Services
SQL Server 2005 SQL CLR Integration
SQL Server 2005 SQL Query Tuning

Use OBJECTPROPERTY To Find Out Table Properties

How many times did you open up a table in design view to find out if a table has
a delete trigger
a clustered index
an identity column
a primary key
a timestamp
a unique constraint
etc etc?

There is an easier way to find out all this info by using the OBJECTPROPERTY function
You will have to get the object id from the table to pass it into the OBJECTPROPERTY function.
To get the object id you can use the OBJECT_ID function.
Run the code below in the Northwind database to see how it works

USE Northwind

SELECT @objectID =OBJECT_ID('customers')

select OBJECTPROPERTY(@objectID,'TableDeleteTrigger') AS 'Table Has A Delete Trigger',
OBJECTPROPERTY(@objectID,'TableHasClustIndex') AS 'Table Has A Clustered Index',
OBJECTPROPERTY(@objectID,'TableHasIdentity') AS 'Table Has An Identity Column',
OBJECTPROPERTY(@objectID,'TableHasPrimaryKey') AS 'Table Has A Primary Key',
OBJECTPROPERTY(@objectID,'TableHasTimestamp') AS 'Table Has A Timestamp',
OBJECTPROPERTY(@objectID,'TableHasUniqueCnst') AS 'Table Has A Unique Constraint',

Lookup OBJECTPROPERTY in Books On Line to find out about additional properties

Saturday, November 19, 2005

Feature Pack for Microsoft SQL Server 2005

The Feature Pack is a collection of standalone install packages that provide additional value for SQL Server 2005. It includes:
Latest versions of redistributable components for SQL Server 2005
Latest versions of add-on providers for SQL Server 2005
Latest versions of backward compatibility components for SQL Server 2005

Go here (http://www.microsoft.com/downloads/details.aspx?familyid=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en) to get to the page

The following things can be downloaded from that page

Microsoft ADOMD.NET
ADOMD.NET is a Microsoft .NET Framework object model that enables software developers to create client-side applications that browse metadata and query data stored in Microsoft SQL Server 2005 Analysis Services. ADOMD.NET is a Microsoft ADO.NET provider with enhancements for online analytical processing (OLAP) and data mining.

Microsoft Core XML Services (MSXML) 6.0
Microsoft Core XML Services (MSXML) 6.0 is the latest version of the native XML processing stack. MSXML 6.0 provides standards-conformant implementations of XML 1.0, XML Schema (XSD) 1.0, XPath 1.0, and XSLT 1.0. In addition, it offers 64-bit support, increased security for working with untrusted XML data, and improved reliability over previous versions of MSXML.

Microsoft OLEDB Provider for DB2
The Microsoft OLE DB Provider for DB2 is a COM component for integrating vital data stored in IBM DB2 databases with new solutions based on Microsoft SQL Server 2005 Enterprise Edition and Developer Edition. SQL Server developers and administrators can use the provider with SQL Server Integration Services, SQL Server Analysis Services, Replication, and Distributed Query Processor. Run the self-extracting download package to create an installation folder. The single setup program will install the provider and tools on both x86 and x64 computers. Read the installation guide and Readme for more information.

Microsoft SQL Server 2000 PivotTable Services
PivotTable Services 8.0 is the OLE DB provider for SQL Server 2000 Analysis Services and is used to connect with an Analysis Services 2000 server. PivotTable Services does not work with SQL Server 2005 Analysis Services. Therefore, client applications that need connect to Analysis Services in both SQL Server 2000 and SQL Sever 2005 will need to install both PivotTable Services 8.0 and Analysis Services 9.0 OLE DB Provider in a side-by-side configuration.

Microsoft SQL Server 2000 DTS Designer Components
The Microsoft SQL Server 2000 Data Transformation Services (DTS) package designer is a design tool used by developers and administrators of SQL Server 2005 servers to edit and maintain existing DTS packages until they can be upgraded or recreated in the SQL Server 2005 Integration Services package format. After installing this download, SQL Server 2005 users can continue to edit and maintain existing DTS packages from the Object Explorer in SQL Server 2005 Management Studio and from the Execute DTS 2000 Package Task Editor in Business Intelligence Development Studio, without needing to reinstall the SQL Server 2000 tools. The DTS package designer in this download was formerly accessed from the Data Transformation Services node in SQL Server 2000 Enterprise Manager.

Microsoft SQL Server Native Client
Microsoft SQL Server Native Client (SQL Native Client) is a single dynamic-link library (DLL) containing both the SQL OLE DB provider and SQL ODBC driver. It contains run-time support for applications using native-code APIs (ODBC, OLE DB and ADO) to connect to Microsoft SQL Server 7.0, 2000 or 2005. SQL Native Client should be used to create new applications or enhance existing applications that need to take advantage of new SQL Server 2005 features. This redistributable installer for SQL Native Client installs the client components needed during run time to take advantage of new SQL Server 2005 features, and optionally installs the header files needed to develop an application that uses the SQL Native Client API.

Microsoft SQL Server 2005 Analysis Services 9.0 OLE DB Provider
The Analysis Services 9.0 OLE DB Provider is a COM component that software developers can use to create client-side applications that browse metadata and query data stored in Microsoft SQL Server 2005 Analysis Services. This provider implements both the OLE DB specification and the specification’s extensions for online analytical processing (OLAP) and data mining.
Note: Microsoft SQL Server 2005 Analysis Services 9.0 OLE DB Provider requires Microsoft Core XML Services (MSXML) 6.0, also available on this page.

Microsoft SQL Server 2005 Backward Compatibility Components
The SQL Server Backward Compatibility package includes the latest versions of Data Transformation Services 2000 runtime (DTS), SQL Distributed Management Objects (SQL-DMO), Decision Support Objects (DSO), and SQL Virtual Device Interface (SQLVDI). These versions have been updated for compatibility with SQL Server 2005 and include all fixes shipped through SQL Server 2000 SP4.

Microsoft SQL Server 2005 Command Line Query Utility
The SQLCMD utility allows users to connect, send Transact-SQL batches, and output rowset information from SQL Server 7.0, SQL Server 2000, and SQL Server 2005 instances. SQLCMD is a replacement for ISQL and OSQL, but can coexist with installations that have ISQL or OSQL installed.
Note: Microsoft SQL Server 2005 Command Line Query Utility requires Microsoft SQL Server Native Client, also available on this page.

Microsoft SQL Server 2005 Datamining Viewer Controls
The Data Mining Web Controls Library is a set of Microsoft Windows Forms controls that enable software developers to display data mining models created using Microsoft SQL Server 2005 Analysis Services in their client-side applications. The controls in this library display the patterns that are contained in Analysis Services mining models.
Note: Microsoft SQL Server 2005 Datamining Viewer Controls requires Microsoft SQL Server 2005 Analysis Services 9.0 OLE DB Provider, also available on this page.

Microsoft SQL Server 2005 JDBC Driver
In its continued commitment to interoperability, Microsoft will release and support a new Java Database Connectivity (JDBC) driver for SQL Server 2005. The SQL Server 2005 JDBC Driver download is available to all SQL Server users at no additional charge and provides access to SQL Server 2000 and SQL Server 2005 from any Java application, application server, or Java-enabled applet. This is a Type 4 JDBC driver that provides de-facto database connectivity through the standard JDBC application programming interfaces (APIs) available in J2EE (Java2 Enterprise Edition).

Microsoft SQL Server 2005 Management Objects Collection
The Management Objects Collection package includes several key elements of the SQL Server 2005 management API, including Analysis Management Objects (AMO), Replication Management Objects (RMO), and SQL Server Management Objects (SMO). Developers and DBAs can use these components to programmatically manage SQL Server 2005.
Note: Microsoft SQL Server 2005 Management Objects Collection requires Microsoft Core XML Services (MSXML) 6.0 and Microsoft SQL Server Native Client, also available on this page.

Microsoft SQL Server 2005 Mobile Edition
Use SQL Server 2005 Mobile Edition (SQL Server Mobile) to rapidly develop applications that extend enterprise data management capabilities to mobile devices. For the latest SQL Server Mobile add-ins, updates, tools, and components, visit the SQL Server Mobile Download site.

Microsoft SQL Server 2005 Notification Services Client Components
The SQL Server 2005 Notification Services Client Components package provides client APIs that enable subscription management and event submission within custom applications that include SQL Server 2005 Notification Services functionality. The subscription management APIs allow developers to create subscriptions and subscribers, and manage subscriber devices. The event submission APIs allow users to specify events using the event APIs or stored procedures.

Microsoft SQL Server 2005 Upgrade Advisor
Upgrade Advisor analyzes instances of SQL Server 7.0 and SQL Server 2000 in preparation for upgrading to SQL Server 2005. Upgrade Advisor identifies deprecated features and configuration changes that might affect your upgrade, and it provides links to documentation that describes each identified issue and how to resolve it.

Microsoft .NET Data Provider for mySAP Business Suite, Preview Version
SQL Server 2005 includes support for accessing SAP data by using the Microsoft .NET Data Provider for mySAP Business Suite. This provider lets you create an Integration Services package that can connect to a mySAP Business Suite solution and then execute commands to access data via supported interfaces. You can also create Reporting Services reports against a server running the mySAP Business Suite.You can use the Microsoft .NET Data Provider for mySAP Business Suite in the SQL Server Import and Export Wizard and in various Integration Services features (including the Script task, the DataReader Source component, and the Script component), as well as the data processing extensions in Reporting Services.The Microsoft .NET Data Provider for mySAP Business Suite is not included in SQL Server 2005. The preview version is licensed as pre-release software as outlined in the License Terms. See the Readme included with the download for information on the prerequisites for using the Microsoft .NET Data Provider for mySAP Business Suite.

Reporting Add-In for Microsoft Visual Web Developer 2005 Express
The Reporting Add-In for Microsoft Visual Web Developer 2005 Express includes a ReportViewer control, an integrated report designer, and a comprehensive API that lets you customize run-time functionality. You can use the control to add interactive real-time data reports to your ASP.NET Web applications. Reports can use data from any ADO.NET DataTable or custom Business object. You can create reports that combine tabular, matrix, and visual data in free-form or traditional report layouts. An integrated report designer is included so that you can create the custom reports that bind to the control.The Reporting Add-In is the same reporting component that is included with other editions of Visual Studio, but without support for Windows Forms applications. For more information including product documentation and samples, see the ReportViewer Controls (Visual Studio) topic on MSDN.

Friday, November 18, 2005

SQL Server 2005 Launch In Philadelphia

I have attended the SQL Server 2005 Launch In Philadelphia. It was very informative I learned some stuff I didn't know and saw some usefull implementations of the new features. There were about 30-40 vendors present. The one vendor that I hoped would be there was not. This company is red-gate and they are the makers of a product called SQL Compare I have used this product for about 2 years now and was hoping to speak to someone and letting them know how much I liked their product. The Architecting Scalable Flexible and Secure Database Systems track was interesting as well as all the others. What kind of goodies did you receive here? Of course everyone received SQL 2005 Standard and Visual studio 2005 Standard Editions. Also included was Windows 2003 Server R2 RC1, Biztalk server 2006 CTP, A free exam voucher, free Biztalk 2006 Developer Edition download (after registering for the beta download) and a shirt of course (ironically Philadelphia is not mentioned on the shirt).

Perhaps the best give away was the Launch 2005 Resource DVD, it is packed with all kinds of stuff. For SQL Server these are
Case Studies
Datasheets and More
Launch 2005 - Data Platform Track

All in all a good event and I am glad I went

Tuesday, November 15, 2005

Find all Primary and Foreign Keys In A Database

To find all your foreign and primary keys in your database run the code below.
The ouput will return the primary key, primary key table, foreign key, foreign key table. Primary keys that don't have foreign keys will have N/A in the foreign key output

USE Northwind

SELECT tc.TABLE_NAME AS PrimaryKeyTable,
COALESCE(tc2.TABLE_NAME,'N/A') AS ForeignKeyTable

Monday, November 14, 2005

SQL Server 2005 Book Rant

I have 2 store credits one for Borders and the other one for Barnes and Noble. So I decided to buy the Pro SQL server 2005 and SQL Server 2005 Administrators Companion this Saturday. I first went to Barnes and Noble and no books. So that already damped my mood. Next I decided to go to Borders and the same thing no books either. This really made me furious, how long does it take for a store to get the books? I wanted instant gratification and I can’t have any. So I went home and ordered them on Amazon I just hope I will get them by Wednesday.

Thursday, November 10, 2005

Cannot add, update, or delete a job that originated from an MSX Server

Well this is one of those very friendly error messages that when you look at it you know immediately what is going on. Of course I am being sarcastic here. This happened to a client who was migrating their servers and backed up all the SQL server Databases and restored them on the new machine they bought. What happened is this, they named the new machine differently than the old machine. When you look at the jobs you can see them (and that’s about it). You can not delete, update or run these jobs. Unfortunately renaming the server was not an option for the client. I looked in the sysjobs table in the msdb database and found out that the name stored was the old servers name

SELECT originating_server FROM msdb..sysjobs

I then updated the originating_server fields in the table with the new server name value and everything was fine after that. As far as I know this doesn't effect SQL server 7 since it stores (local) in the originating_server column

Tuesday, November 08, 2005

Pad Numbers By Using CASE, LEFT And CONVERT

Let's say you have a table with integer values below 100000 and you want them in the same format with leading zeros. For example 500 has to be 000500 and 1 has to be 000001
How do you do this in SQL server?
Below are two ways to accomplish this.

CREATE TABLE #ValueTable (value INT)
SELECT 50000

--Use CASE, LEN and CONVERT to pad the values
SELECT value,CASE LEN(value)
WHEN 1 THEN '00000' + CONVERT(VARCHAR,value)
END AS Formattedvalue
FROM #ValueTable

--Use LEFT, LEN and CONVERT to pad the values
SELECT value,LEFT('000000',(6 -LEN(value )))
+ CONVERT(VARCHAR,value) AS Formattedvalue
FROM #ValueTable

I have received a comment from Rob Farley who was so kind to point out to me that I should have used RIGHT instead of left
Here is the code he supplied

--Use RIGHT to pad the value
SELECT value, RIGHT('000000' + CONVERT(VARCHAR,value),6) AS FormattedValue
FROM #ValueTable

Monday, November 07, 2005

SQL Server 2005 launch Webcast

Today at 9AM Pacific Standard Time Steve Ballmer launches Microsoft SQL Server 2005, the next generation data management and analysis software. You can follow the launch, including a Webcast of the launch from this Web site:

SQL Server product site: http://microsoft.com/sql
SQL Server Developer Center: http://msdn.microsoft.com/sql
SQL Server TechCenter: http://technet.microsoft.com/sql/
Data Access and Storage Developer Center: http://msdn.microsoft.com/data

Friday, November 04, 2005

SQL Server Podcast (SQL Down Under show 8)

SQL Down Under show 8 with SQL MVP Adam Machanic discussing stored procedures as APIs and unit testing SQL Server is now available for download from www.sqldownunder.com

These podcasts are great make sure you check them out

Thursday, November 03, 2005

Formatting Data By Using CHARINDEX And SUBSTRING

Let's say you have names stored in the format [Klein, Barbara] but would like it to be [Barbara Klein]
How do you accomplish that in SQL?
SQL provides 2 useful functions (CHARINDEX And SUBSTRING)
Run the code below to see how they work

CREATE TABLE Names (ID INT identity not null,NameField VARCHAR(50), ProperNameField VARCHAR(50))

SELECT 'Klein, Barbara',NULL
SELECT 'Smith, John',NULL
SELECT 'Jackson, Michael',NULL
SELECT 'Gates, Bill',NULL

SET ProperNameField =SUBSTRING(NameField,CHARINDEX(',',NameField) + 2,
LEN(NameField) - CHARINDEX(',',NameField))
+ ' ' + LEFT(NameField,CHARINDEX(',',NameField)-1)


Wednesday, November 02, 2005

Finding ASCII, Numbers and Alphabet Characters In SQL Server Tables

SQL Server has limited support for regular expressions,
You can run the code below to see what some of the results are by searching for data while using regular expressions

CREATE TABLE AsciiTest (id INT identity, TextField VARCHAR(50))
SELECT '%&&&123%#$#$'
SELECT 'safdsfsdrfsdfse'
SELECT '12121212'
SELECT '1212asasas'
SELECT '%&&&%#$#$'
SELECT '4564gg565656'

--No Alphabet Characters
WHERE TextField NOT LIKE '%[a-Z]%'

--Starting with a number
WHERE TextField LIKE '[0-9]%'

--Ending with a number
WHERE TextField LIKE '%[0-9]'

--Numbers and characters
WHERE TextField LIKE '%[0-Z]%'

--Only non alphabet/numbers characters
WHERE TextField NOT LIKE '%[0-Z]%'

--some non alphabet/number characters
WHERE TextField LIKE '%[^0-Z]%'

-- ASCII Code 38 (&)
WHERE TextField LIKE '%' + char(38) + '%'

Tuesday, November 01, 2005

Top Google Searches On SQL Server Code

These are the top SQL Searches on this site for the month of October.
I have left out searches that have nothing to do with SQL Server or programming
Here are the results...

non-ANSI outer join
veritas 10 sql module
backup log files
Free SQL Code help
query analiser

An interesting list, lets say what next month will bring