tags:

views:

71

answers:

1
+1  Q: 

SQL Server Query

Hi,

I'm trying to do some work with my SQL table.

I have 2 buildings with room numbers 1 - 100 in building 1 and 101 - 199 in building 2. I have a location field (which I've just created) and want to run a query to populate it with either 'Building 1' or 'Building 2' depending on which room number it has in the 'Room' field.

Many thanks for your help.

Regards

Scott

+4  A: 

You can use Case to update your table:

Update your_table
Set location = Case When room_number <= 100 Then
                       'Building 1'
                    Else
                       'Building 2'
                    End;

If all of your room-numbers have three digits followed by some other characters, using substring should work:

Case When Cast( Substring( room_number, 1, 3 ) As Int ) <= 100 Then

Since not all of your rooms start with three digits (1A) you can use PatIndex to find the length of the number:

Case When
   Cast(
      Substring( room_number, 1, PatIndex( '%[A-Z]%', room_number || 'A' ) - 1 )
   As Int ) <= 100
Then

I'm concatenating the A to make sure it also works with numerical room-numbers.

Peter Lang
Thanks. How would I get it to cope with room numbers such as 120Z and 121Y ?
Scott Jackson
If all of your room numbers are 3 digits and a single character, you could use a SUBSTRING on the room number and compare that value in the case statement.
Ardman
My room numbers go from 1 to 500 and have others inbetween such as 120X, 121G, etc (only about 20 rooms though).
Scott Jackson
Would it make it a real pain if my room field was nvarchar ? (which it is)
Scott Jackson
@Scott Jackson: Please check my updated answer.
Peter Lang
Thanks. When I run it I get an error....'Syntax error converting the nvarchar value '1A' to a column of data type int'
Scott Jackson
@Scott Jackson: Please see my next update. Can't try it right now, not sure if the offset (`-1`) is correct.
Peter Lang