Link to home
Start Free TrialLog in
Avatar of Itudk_2010
Itudk_2010

asked on

T-SQL query explaination

Hi all,

I have some problems understanding the following query. Do you know what the following query does?

SELECT
      CASE
      WHEN CHARINDEX(' ',RecipeName) <> 0 THEN
      SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1,
      case
      when charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName))) = 0 then LEN(RecipeName)
      else charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName)))
     
  end)

ELSE
    'No Second Word'
     END Second_Word
FROM Recipe


Thanks
Avatar of Ephraim Wangoya
Ephraim Wangoya
Flag of United States of America image

CHARINDEX serchers for a specified substring within a string and returns the position of the substring
SUBSTRING copies a specified number of characters from a string starting from a given index

 WHEN CHARINDEX(' ',RecipeName) <> 0 THEN
      SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1,

If there is a space in the recipe, then copy all characters up to the space
eg if its "salt sugar pepper"
then you end up with "Salt"

when charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName))) = 0 then LEN(RecipeName)
      else charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName)))

Now we look for the second space character and get the string
eg "sugar"

Avatar of Itudk_2010
Itudk_2010

ASKER

Hi ewangoya,

Thanks for the explaination. I still don't understand the following part?

when charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName))) = 0 then LEN(RecipeName)
      else charindex(' ', SUBSTRING(RecipeName,CHARINDEX(' ',RecipeName) + 1, LEN(RecipeName)))

Looking forward to your reply.
SOLUTION
Avatar of JoeNuvo
JoeNuvo
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
good