0

Using SQL Scripts, I need to validate Comma Separate value. How should i validate the String Variable ?

Validation should be both Right / Left Trim for each value and there should not be any special characters such as Comma or Period for the last value.

 create table #test
 (col varchar(100))

 insert into #test values
 ('1,2'),
 ('1,2,'),
 ('1,'),
 ('1,2,3,4,5')


 select * from #test

In the above query, for the second value - Expected Result is 1,2 In the above query, for the Third value - Expected Result is 1

2
  • What exactly do you mean by "validate from SQL"? Do you need an SQL that returns all invalid values? Or all valid ones? Or an extra field indicating whether the name is valid or not? Commented Jun 11, 2016 at 19:17
  • @Heinzi, i have edited my posting with clear explanation. Commented Jun 11, 2016 at 19:22

2 Answers 2

1

You can update your table to fix "offensive" values.

update #test
set col = substring(col, 1, len(col) - 1)
where col not like '%[0-9]'

This will remove last character where value doesn't end by a digit.

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

2 Comments

Your syntax logic helps me. This resolves the data issue, I can tweak it according to my needs. Thanks a lot !!
Will you please help me in this posting : stackoverflow.com/questions/37766643/…
1

You can use a check constraint. You seem to want something like this:

alter table t add constraint chk_name as
    (name like '%,%' and
     name not like '%,%,%' and
     name not like '%[^a-zA-Z,]%'
    )

SQL Server doesn't have support for regular expressions. This implements the rules:

  • Name has to have a comma
  • Name does not have two commas
  • Name consists only of alphabetic characters and a comma

You may find that you need slightly more flexibility, but this handles the cases in your question.

3 Comments

i cant alter the table. I have to work on the data part. database belongs to third party.
@goofyui . . . You can use the same logic in a where or case. Your question states that you want to validate data and that is what a check constraint does.
Thank you Gordon, Not sure whether i was able to get it. I tried with sample query, it didnt work. I have posted a Sample Temp table query in the original posting. Please take a look.

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.