简体   繁体   中英

What is wrong with this query, and how can I make it more efficient?

I have a ProjectNum column that contains a string data type . Normally the numbers are X1234... but if there is no number assigned, then one must be autogenerated and depending on the priority assigned to the project depends whether it begins with C or F . So an autogenerated number must begin with C or F and be followed by six digits and also auto-increment. So here is my query...

SELECT MAX(CINT(RIGHT(ProjectNum, 6))) AS LastDigits
FROM project_master_query
WHERE ((ProjectNum LIKE (IIF([@priorityDefID] = 4, "C*", "F*"))));

This allows me to grab the last auto-incremented number and then I can autogenerate a number in code by adding 1. The issue is, when I send in @priorityDefID of 4 (and at the moment there are none in the database that begin with "C"), I receive the error "This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables."

Not quite sure why this comes up with I pass 4, but a 1, 2 or 3 work fine and return the correct value. I was thinking of instead of writing MAX , just grabbing all of them that begin with C or F and then grab the right 6 digits, order by descending and grabbing the top 1?

That query has numerous issues and I'm not really clear about what all is going on so I don't know where to start. However I can warn you about a danger of using CInt() with 6 digits. CInt("999999") throws an overflow error because the maximum integer value is 32,767. You would be safer to use CLng because the maximum long integer value is 2,147,483,647 ... so a long integer will accommodate all possible 6 digit values.

Although that issue may not be a source of trouble with the present ProjectNum values, it's something which may bite you in the future as you store more ProjectNum values.

Regarding "[the error message] comes up with I pass 4, but a 1, 2 or 3 work fine and return the correct value" , you also said "at the moment there are none in the database that begin with 'C'" . That means the query returns no rows in that situation. I suspect that would cause a problem with RIGHT(ProjectNum, 6) because Right(Null, 6) triggers an invalid use of Null error.

Check whether the error goes away after you add a row with a ProjectNum which begins with "C" .

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