tags:

views:

100

answers:

2

I have a column that stores data like (42,12). Now I want to fetch 42 or 12 (two different select queries). I have searched and found some similar but much more complex scenarios. Is there any easy way of doing it? I am using MSSQL Server 2005.

Given there will always be only two values and they will be integer

+4  A: 

You can try something like this

DECLARE @Table TABLE(
     Val VARCHAR(50)
)

INSERT INTO @Table (Val) SELECT '42,12'

SELECT  *,
     CAST(LEFT(Val,CHARINDEX(',',Val)-1) AS INT) FirstValue,
     CAST(RIGHT(Val,LEN(Val) - CHARINDEX(',',Val)) AS INT) SecondValue
FROM    @Table
astander
+8  A: 

I will help you here by telling you that the reason you have this problem is because the database (which you may not have any control over), violates first normal form. Among other things, first normal form says that each column should hold a single value, not multiple values. This is bad design.

Now, having said this, the first solution that pops into my head is to write a UDF that parses the value in this column, based on the delimeter and returns either the first or second value.

Randy

Randy Minder
Agree with UDF's, and the comment about bad design... Since you state there will only ever be two values, then use two dbFields.
GordonB
The schema is defined long time ago and at that time the requirements was not there. Also I can not change the schema now as it will break everything. Also the table is used as all purpose. ( There might be other values in that column for other type of information for other types that I don't care.
Tanmoy
+1 for 1NF violation i.e. non-scalar values.
onedaywhen