简体   繁体   English

使用SUBSTRING和LEN的SQL问题

[英]SQL Issue using SUBSTRING and LEN

SELECT [Code], [Due Date Calculation],

--original string that is causing the error
--SUBSTRING([Due Date Calculation], 1, LEN([Due Date Calculation]) - 1) as OG,

--here are the tests that run fine by themselves
LEN([Due Date Calculation]) - 1 as Test1,
SUBSTRING([Due Date Calculation], 1, 2) AS Test2, 
SUBSTRING([Due Date Calculation], 1, LEN([Due Date Calculation])) AS Test3 

FROM [TEST]

Here is the error I am getting: 这是我得到的错误:

Msg 537, Level 16, State 2, Line 1 Invalid length parameter passed to the LEFT or SUBSTRING function. 消息537,级别16,状态2,行1无效的长度参数传递给LEFT或SUBSTRING函数。

I know it has something to do with the way SQL is rendering the data. 我知道它与SQL呈现数据的方式有关。 The data displays a small upside down 'L' when I query it using SQL, but it simply shows a 'D' in the front end. 当我使用SQL查询数据时,数据显示一个小的上下颠倒的“ L”,但在前端仅显示一个“ D”。 I don't have a good enough reputation to include the images. 我没有足够好的声誉来包含这些图像。 An example of a typical Codes are 30D , 60D , 120D , 365D , etc. 典型代码的示例是30D60D120D365D等。

I need to drop the trailing D and display what is left. 我需要删除结尾的D并显示剩余的内容。

Thanks for the help. 谢谢您的帮助。

Here are the results from the SQL Query: [ https://drive.google.com/file/d/0B1cL-bzbZ4IzU2ctYlRNZnJhZjg/view?usp=sharing][1] 以下是SQL查询的结果:[ https://drive.google.com/file/d/0B1cL-bzbZ4IzU2ctYlRNZnJhZjg/view?usp=sharing] [1 ]

If i understand your problem correctly you are looking for this 如果我正确理解您的问题,您正在寻找

Select SUBSTRING([Due Date Calculation],0,CHARINDEX('D',[Due Date Calculation])) 
As [Due Date Calculation]  FROM Test

SQLFIDDLE SQLFIDDLE

Here is my sample 这是我的样品

declare @tbl table
(
    c1 nvarchar(9)
)
insert into @tbl values ('30D')
insert into @tbl values ('120D')
insert into @tbl values ('365D')

select  IIF(RIGHT(c1, 1) = 'D', LEFT(C1, LEN(C1)-1), C1)
from    @tbl

Result 结果
30 三十
120 120
365 365

If you want to cut off the last character, just do it like this. 如果您想剪掉最后一个字符,就这样做。

DECLARE @String VARCHAR(100) = '123D'

SELECT SUBSTRING(@String,0,LEN(@String))

Or if you have multiple characters at the end, then try this which will grab until the numbers stop. 或者,如果末尾有多个字符,请尝试执行此操作,直到数字停止为止。

DECLARE @String VARCHAR(100) = '123D'

SELECT SUBSTRING(@String,0,PATINDEX('%[^0-9]%',@String))

Both have same results: 两者都有相同的结果:

123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM