SQL语句在某个字符之前返回

时间:2013-07-25 13:28:06

标签: sql string sql-server-2008

我需要能够输出一个字符串,该字符串将返回指定的字符,我相信使用charindex是解决此问题的最佳方法,但我不确定所需的语法。

一些例子:

  • 如果字符串等于"601-Test-Test2_Test3",那么我希望返回601
  • 如果字符串等于"42-Test_test3",那么我希望返回42
  • 如果字符串等于"1-Test_test3",那么我希望返回1

1 个答案:

答案 0 :(得分:1)

-- this should do what you require:

DECLARE @string nvarchar(50)

SET @string = '601-Test-Test2_Test3'

SELECT @string as 'test string', left(@string, charindex('-', @string) - 1) AS 'Upto-'
相关问题