The issue: I am writing a web app to track agreements where each agreement can have one, or multiple, account numbers associated with them, like so:
Agreement No. 1: Account Numbers = XYZ-123-123-123; XYZ-123-123-456; XYZ-123-123-789
Agreement No. 2: Account Numbers = XYZ-123-123-333
Agreement No. 3: Account Numbers = XYZ-123-123-123; XYZ-123-123-789
I quickly decided to store the account numbers in a separate table so that each agreement could have a variable number of account numbers associated with it:
Agreement_Account_Numbers table
Agreement_ID Account_Number
1 XYZ-123-123-123
1 XYZ-123-123-456
1 XYZ-123-123-789
2 XYZ-123-123-333
3 XYZ-123-123-123
3 XYZ-123-123-789
But then I ran into the problem of how to display all of an agreements account numbers in a table listing a number of agreements. I wanted an SQL query that would return one agreement per line, with all of the account numbers for each agreement concatenated in a single field. In MySQL this would be easy: do JOIN query with the agreements table linked by Agreement_ID to the on the agreement ID and then GROUP BY Agreement_ID and use the group_concat function to concatenate the Account_Number field. However, for this project I have to work with MS SQL Server and it apparently does not have any such function. Googling around led me to this excellent question on stackoverflow:
Simulating group_concat MySQL function in MS SQL Server 2005?
It
took me a while to sort out which answer to this question was easiest to implement, so I
am writing down what worked for me for my own future reference. Here is what I ended up with:
SELECT
Agreement_ID,
STUFF(
(SELECT '; ' + Account_Number
FROM agreement_account_numbers
WHERE agreement_id = a.agreement_id
FOR XML PATH (''))
, 1, 1, '') AS Account_Numbers
FROM Agreement_Account_Numbers AS a
GROUP BY agreement_id
The result of this query is:
Agreement_ID Account_Numbers
1 XYZ-123-123-123; XYZ-123-123-456; XYZ-123-123-789
2 XYZ-123-123-333
3 XYZ-123-123-123; XYZ-123-123-789
This query uses a sub-select clause to retrieve all of the account numbers for each agreement by linking the Agreement_Account_Numbers table back to itself (by giving the table the alias "a") and then putting sub-select results in a string using the MS SQL Server specific command FOR XML PATH (''). Then the STUFF function replaces the first character in the sub-select result string with a zero length string ('') to strip off the leading semi-colon that would otherwise be in front of the first account number.
The command is actually FOR XML with the PATH option specified, and then the tag to surround each row specified to be nothing (''). I tried figure out exactly now FOR XML works, and what the PATH option means, but as usual I found the MS documentation to be completely cryptic so I just accepted that it works.
2012-06-18
How to simulate the MySQL group_concat function in MS SQL Server
Posted by
AndyfromTucson
at
09:28
4
comments
Labels: T-SQL, Transact SQL
2012-05-18
How to get MS SQL Server nvarchar() field to sort correctly using ORDER BY
I had an nvarchar field in MS SQL Server that wasn't sorting correctly when I did an ORDER BY on it. For example, 10 would be put before 9 if I sorted ASC. It turns out that MS SQL Server considers the position of each character in the field in sorting, and since the field is nvarchar (variable width) the digits of a number are not in consistent positions in the field. I found the solution in this post on stackoverflow.com:
Order By Clause for NVARCHAR column in SQL Server
The specific code is:
ORDER BY RIGHT(REPLICATE(N' ', 50) + the_column_you_want_to_sort_by, 50)
What this does is virtually add enough leading whitespaces to each entry to make the column look like a fixed width column for the purposes of the query.
Posted by
AndyfromTucson
at
04:59
0
comments
Labels: MS SQL Server, Transact SQL
2010-10-20
Escaping square brackets in SQL Server queries from PHP
I have a PHP web app that pulls data from an SQL Server database using the ODBC functions. Earlier I come up with a PHP function to escape single quotes in user input by adding a single quote to each single quote (a single quote is the character you use to escape a single quote) as defense against (inadvertent) SQL injection (the web app is behind a firewall).
The other day I accidentally discovered that including text inside a pair of square brackets [like this] in user input that was added to a LIKE clause of a WHERE clause resulted in a huge data dump being returned by SQL Server. I did some Googling and discovered that characters enclosed in square brackets have some special meaning in SQL Server (I don't remember what it was). I first tried updating my PHP function to escape square brackets with single quotes, but that didn't work for some reason. Then I did some more research and discovered that the way to escape a square bracket in SQL Server is to enclose it in square brackets like this [[]. So I updated my PHP function to do this on user input and it worked to stop the data dumps when a user included something like [fred] in their input.
Writing the PHP to do this was tricky because if you just do a straight str_replace on each square bracket the second replace replaces some of the square brackets you added with the first replace and messes it all up. The way I solved this was to write my function to:
- first replace the left square bracket with an arbitrary three character string that is unlikely to be in user input,
- then replace on the right square bracket with []],
- then do a third replace of my arbitrary three character string with [[].
Posted by
AndyfromTucson
at
06:37
0
comments
Labels: SQL, Transact SQL
2009-07-30
Transact SQL for including concatenated text fields in WHERE clause
I am working with a database on an SQL Server that carries forward a legacy table structure where the description field for a Purchase Order line item is spread across multiple text columns in the table. In other words, instead of having one 250 character text field for the item description it has a total of 7 text fields of (I think) about 25 characters each. I have a web application where users can search for purchase orders using the description fields. My original solution was to check for the user's search term across each of the seven text fields using OR clauses. However, this meant that a user's search term would not be found if it happened to straddle the border between two of the seven fields.
To solve this problem I tried concatenating all of the description fields and then testing the concatenated string using LIKE, but that resulted in some POs not being inlcuded in the results when they should have been. I finally puzzled out that what was happening was that database treated empty description fields as null and Transact SQL gives a null value for the whole concatenation if you try to concatenate a number of valid string values with one null value. In other words if you concatenate Field1 + Field2 + Field3, and the first two fields have text in them, but Field3 does not, then Transact SQL will give you a null result. So the solution was to use ISNULL to convert null description fields to zero length strings when concatenating them for the WHERE clause, so that one null value doesn't ruin the whole concatenation, like so:
WHERE Field_1 + ISNULL(Field_2,"") + ISNULL(Field_3,"") + ISNULL(Field_3,"") LIKE %search-term%
Posted by
AndyfromTucson
at
08:38
0
comments
Labels: SQL, Transact SQL