简体   繁体   中英

Access query vs SQL Server 2008 query

I'm trying to convert this query from an Access db to work in SQL Server 2008 and got stuck. I know there are differences, but I'm not sure what's going on and apparently I'm not very good at this. Any help would be appreciated.

Access

Mid(Trim([SC01039]),
InStrRev(Trim([SC01039])," ")+3,4)
AS ProductType

SQL Server 2008 (This is what I tried changing it to)

Substring(RTrim(LTrim([SC01039])),
Right(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039]))))+3,4) 
AS ProductType

The error I receive is

"Conversion failed when converting the nvarchar value 'L318' to data type int."

Why is it trying to convert the resulting text into an integer? My assumption is the query is saying, "Find the position of the space closest to the right of the string, now add 3 to that position and give me the next 4 characters." It seems to be a problem with the data, not the query (what does it do if there is no space? Or the string is null?) I dunno...

Did I even get close? :P

There are mixed characters in SC01039, but this is a sample:

SC01039         :     Expected Output
-------------   :     ---------------
QC   06999911   :     9999
SW   12FMT116   :     FMT1
26RMF399        :     RMF3
08              :     [empty]
[empty]         :     [empty]

Apparently it is always 4 characters, starting 3 to the right of the first space found (searching for the space from right-to-left). Some data in SC01039 have multiple spaces (ie: 09 TVR 012 2, in this case it doesn't return anything and I believe that is OK).

You problem is with Right(RTrim(LTrim([SC01039])), part of your code. Why do you need it? Because what I've shown below should do the trick.

Try this:

Substring(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039])))+3,4) 
AS ProductType

The Substring is expecting SUBSTRING(expression, start, length) and you provided the second parameter with a nvarchar;

Right(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039]))))+3

hence your error.

Create this function (you don't have to put it helps with readability

CREATE FUNCTION InStrRev(@Val nvarchar(max), @substr nvarchar(max))
RETURNS int
AS
BEGIN
RETURN CASE WHEN CHARINDEX(@substr, RTrim(LTrim(Reverse(@Val)))) = 0 THEN 0 ELSE LEN(@Val) - CHARINDEX(@substr, RTrim(LTrim(Reverse(@Val)))) + 1 END  -- add one because you want a start position
END

and use it in your code like this

Substring(RTrim(LTrim([SC01039])), dbo.InStrRev([SC01039], ' ') + 3, 4) AS ProductType

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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