Link to home
Start Free TrialLog in
Avatar of spirose
spirose

asked on

SQL syntax for parsing

I have a table TableA with the following  field value for column 'Property'
[EmployeeID]|ASC;[AddressID]|DESC        

Then I need the output as
EmployeeID ASC, AddressID DESC (eliminating the pipes in the same order as they appear)
If there were sorts on other columns, then it would be appended following a semicolon.

We cannot predetermine on how many columns the sorting is done..
So the value of 'Property' could be:
[EmployeeID]|ASC;[AddressID]|DESC;[Name]|ASC;[Title]|DESC   (and so on)
The above field value for 'Property' in this case needs to be parsed to get the following value:
ORDER BY EmployeeID ASC, AddressID DESC, Name ASC, Title DESC
       
Avatar of cmgarnett
cmgarnett
Flag of United Kingdom of Great Britain and Northern Ireland image

If you use a user defined function or stored procedure, you can build up your SQL command as a string and use the replace function to substitute the ";" characters for a "," character.

Once the string contains the parsed command, you can then use the EXEC('string with command') the run the real query and then return the results.

That way you can pass your sort order string into the function/procedure. It can parse it for you and then return the results of the search.
'order by '+replace(replace(property,';',','),'|',' ')
Avatar of spirose
spirose

ASKER

Thanks lowfatspread but one more Question how do you incorporate changes like this?

[EmployeeID]|0;[AddressID]|1;[Name]|0;[Title]|1   (and so on)

If it is 0 then DESC and if it is 1 then ASC in the code you provided above...
thanks
ASKER CERTIFIED SOLUTION
Avatar of Lowfatspread
Lowfatspread
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of spirose

ASKER

Thanks