patternsqlMinor
RIGHT() works in a SELECT but not in an UPDATE?
Viewed 0 times
updatebutworksselectnotright
Problem
I am trying to run a script which does some work including stripping the leading two characters from the string inside each row of a column. To do this I am using
Invalid length parameter passed to the RIGHT function
why is it failing in the
RIGHT() and it works fine when I use it in a SELECT..FROM but when I use that same code inside an UPDATE it fails withInvalid length parameter passed to the RIGHT function
why is it failing in the
UPDATE but not the SELECT...FROM?USE JobSight;
DROP TABLE #ReleaseTemp;
SELECT A.MajRelease,
A.MinRelease,
A.Build,
Split.a.value('.', 'VARCHAR(MAX)') AS ReleaseNotes
INTO #ReleaseTemp
FROM
(
SELECT MajRelease,
MinRelease,
Build,
CAST ('' + REPLACE(RelNotes, ';;', '') + '' AS XML) AS ReleaseNotes
FROM JobsDB.dbo.ReleaseData
) AS A
CROSS APPLY ReleaseNotes.nodes ('/M') AS Split(a);
UPDATE #ReleaseTemp
SET ReleaseNotes = RIGHT(ReleaseNotes, LEN(ReleaseNotes) - 2);
UPDATE #ReleaseTemp
SET ReleaseNotes = LTRIM(#ReleaseTemp.ReleaseNotes);
SELECT MajRelease,
MinRelease,
Build,
RIGHT(ReleaseNotes, LEN(ReleaseNotes) - 2) AS ReleaseNots
FROM #ReleaseTemp
WHERE #ReleaseTemp.ReleaseNotes <> '';Solution
why is it failing in the
Because in your
Rather than checking for
Please note that I included the
UPDATE but not the SELECT...FROM?Because in your
SELECT you are filtering out the rows via WHERE #ReleaseTemp.ReleaseNotes <> ''. You do not have that filter on your UPDATE statement and you probably have at least one row that has a length of 0 or 1. Try making it:UPDATE #ReleaseTemp
SET ReleaseNotes = LTRIM(RIGHT(ReleaseNotes, LEN(ReleaseNotes) - 2))
WHERE LEN(#ReleaseTemp.ReleaseNotes) > 1;
Rather than checking for
<> '', I changed the filter to ensure that the length of the string is at least 2 characters. This avoids the situation in which the string has only one character which does not equate to an empty string '' but would still get that error when passing in a -1 (from length of 1 minus 2) to the RIGHT function.Please note that I included the
LTRIM() which you currently have as a second step in order to avoid that second DML operation.Context
StackExchange Database Administrators Q#126282, answer score: 8
Revisions (0)
No revisions yet.