2013-07-25 69 views
-2

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

一些例子:

  • 如果字符串等于"601-Test-Test2_Test3"话,我想返回601
  • 如果字符串等于"42-Test_test3"话,我想返回42
  • 如果字符串等于"1-Test_test3"那么我想返回1
+2

什么数据库系统?不同的系统对字符串操作有不同的功能。 –

+2

这显然是一项家庭作业。 –

+0

http://stackoverflow.com/questions/2647/split-string-in-sql – Joel

回答

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-'