0

I need, if possible, a T-SQL query that will return the values in a specific format from the columns.

I can do this programmatically (c#), but is it possible to do in query using SQL Server 2008 ?

Here's the current query

select id, server_name, domain_name 
from mastertable

Current output:

id server_name   domanin_name
1  sys1          one.abc.in
2  sys2          two.pqr.in 
3  sys3          three.abc.in 
4  sys4          four.xyz.in

I need to display data as (skip value after (.) for column domain_name):

id server_name domanin_name
1  sys1        one
2  sys2        two
3  sys3        three 
4  sys4        four

Thanks in advance

2 Answers 2

2

You could try something like:

SELECT id, server_name, SUBSTRING(domain_name, 1, CHARINDEX('.', domain_name) - 1)
FROM mastertable
Sign up to request clarification or add additional context in comments.

6 Comments

Works - as long as you're sure that domain_name will always contain a . - if that's not the case, your query will fall flat on its nose (Msg 537, Level 16, State 2, Line 20 Invalid length parameter passed to the LEFT or SUBSTRING function.) ...
@marc_s But if the field is "domain name", then is it a valid domain name in the first place if it doesn't contain a "."? But in any case, you make a valid point.
Yes - I would assume, too, that such a column would include a . - but I'd rather check to make sure, rather than just assume ... (principle of defensive programming)
SELECT id, server_name, SUBSTRING(domain_name, 1, CHARINDEX('.', domain_name) - 1) FROM mastertable this give one., two. DID LIL EDIT SELECT id, server_name, SUBSTRING(domain_name, 0, CHARINDEX('.', domain_name) - 1) FROM mastertable
Curious, because starting from zero doesn't work for me (end up with "on", "tw", etc. Are you sure you had the -1 after the char index?
|
1

You could use something like this:

SELECT
    id,
    server_name,
    mod_domain_name =
        CASE CHARINDEX('.', domain_name)
            WHEN 0 THEN domain_name
            ELSE SUBSTRING(domain_name, 1, CHARINDEX('.', domain_name) - 1)
        END
FROM mastertable

This tests to make sure there's a . in the domain_name, and if so, it "clips" the domain name to show only the bits before the first .

Comments

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.