Useful MSSQL Queries and Statements

Although I primarily use MySQL on linux servers, I’ve had a couple clients using MSSQL databases for all sorts of things from email marketing to order tracking. For these clients, I use Microsoft SQL Sever Management Studio Express and have saved many of the MSSQL queries I’ve had to create. Some of these will work fine in MySQL as is or with minimal tweaking.

Here’s a collection of the useful MSSQL Queries I’ve used and saved. This is by no means a comprehensive list of all the MSQL Queries and MSSQL statements, but I hope they can be useful for you.

MSSQL Variables

Being able to declare MSSQL Variables has saved so much time for sets queries that I need to run multiple times with slight variations.

This is a very basic example, but has everything you need. MSSQL Variables must begin with a “at symbol” (@). You first declare the MSSQL variables and assign it a character type (in this case, I’m just using varchar(55). 55 is the maximum number of characters to be stored in the variable. Then you set a value for the variables.

Declare @email1 varchar(55), @name1 varchar(55)
set @email1 = ‘%websitesinaflash.com%’
set @name1 = ‘%Ashton Sanders%’

SELECT *
FROMÂ Â email_database
WHERE email_address LIKE @email1
AND first_name LIKE @name1

MSSQL UNION

mssql_connect(): unable to connect to server:

I have a PHP script that I run locally (on my Windows XP Machine) that accesses a MSSQL server using the mssql_connect() function. I used xampp to get PHP on my machine.

Today I finished getting this to work on my second computer. The first time I did this, I also ran into a million problem – but didn’t note any of them. So here I am rectifying my previous mistakes in the hope of not having to search for the same solution next time.

The error I was getting was:

mssql_connect(): unable to connect to server: ‘www.ashtonsanders.com’

(Domain changed for security purposes.)

I handled it by replacing ntwdblib.dll with this ntwdblib.dll.zip in these two folders:

xampp/php
xampp/apache/bin

Enjoy!
-Ashton Sanders
(Note: algorytmy.pl was the final website that helped me handle my problem.)