We help IT Professionals succeed at work.

Can't convert a simple string manipulation operation to a dynamic SQL version in a T-SQL stored procedure

79 Views
Last Modified: 2019-02-26
I have to convert a select statement in a T-SQL stored procedure to dynamic SQL to be able to run that procedure in different DBs, and one line in it fails constantly, it's the following (before conversion):

Left(SecuritiesAccNo, charindex('-', SecuritiesAccNo) -1)

It's a simple statement, taking the content of the SecuritiesAccNo field (defined as nvarchar(18)) from a table, and isolating the characters left of a hyphen found in the field normally at the 7th or 8th character.

I just can't seem to find the version that, as a string, will be executed correctly as part of an exec (@sql) statement. I always get an error with all the various versions I tried.

Can somebody help me there, I'm despairing.

Thanks
Bernard
Comment
Watch Question

lcohanDatabase Analyst
CERTIFIED EXPERT

Commented:
It may be NULL's related and I suggest add a ISNULL or COLEASCE function on the column. Or simply try use PATINDEX instead of CHARINDEX as both CHARINDEX and PATINDEX are used to get starting position of a pattern. The functional difference is that the PATINDEX can use wild characters in the pattern being searched whereas CHARINDEX can't.
Bernard ThouinIT Analyst and developer

Author

Commented:
HI

Thanks for your answer, but in the meantime, I found the right syntax, a bit by chance :) Sorry for the bother.
IT Analyst and developer
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions