1

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

2
  • 1
    @Galwegian: Can't understand why would you delete your post, if the answer is correct? Commented May 5, 2010 at 10:29
  • Galwegian posted an anwer that was correct, but has since deleted it. Commented May 5, 2010 at 10:38

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. How would I get it to cope with room numbers such as 120Z and 121Y ?
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.
My room numbers go from 1 to 500 and have others inbetween such as 120X, 121G, etc (only about 20 rooms though).
Would it make it a real pain if my room field was nvarchar ? (which it is)
Thanks. When I run it I get an error.... 'Syntax error converting the nvarchar value '1A' to a column of data type int'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.