Invalid length parameter passed to the LEFT or SUBSTING function - sql-server

Declare #FileNumber int
Set #FileNumber = cast (SubString(#fileName, CharIndex('Stats', #fileName) + 6, charindex('.',#fileName) - (CharIndex('Stats', #fileName) + 6)) as int)
I'm passing in '' for the #fileName and getting this error. This is in SQL Server 2016

Because ...
select SubString('', 6 , - 6)
Returnes ...
Msg 536, Level 16, State 1, Line 7
Invalid length parameter passed to the substring function.
https://learn.microsoft.com/en-us/sql/t-sql/functions/substring-transact-sql

Related

MS Access mid equivalent in SQL Server

I have the following SQL statement; the problem is that the MID function is not recognized. Is there an equivalent to MID in SQL Server? Thanks
SQL:
SELECT
tblHR_Employees.ADLoginID AS bar,
Replace(LCase(Mid([LikesToBeCalled], 1, 1) & [lastname]), ' ', '') AS foo
FROM
[STONE_DB].[dbo].[tblHR_Employees]
WHERE
tblHR_Employees.ADLoginID IS NULL
AND tblHR_Employees.SeparationDate IS NULL;
Returns:
Msg 195, Level 15, State 10, Line 2
'Mid' is not a recognized built-in function name.
substring() would be the equivalent -- and lower() would be the equivalent of LCase()
SELECT
tblHR_Employees.ADLoginID AS bar,
Replace(LOWER(SUBSTRING([LikesToBeCalled], 1, 1) & [lastname]), ' ', '') AS foo
FROM
[STONE_DB].[dbo].[tblHR_Employees]
WHERE
tblHR_Employees.ADLoginID IS NULL
AND tblHR_Employees.SeparationDate IS NULL;

SQL Server : get part of string between 'ServicePassword=' and '&' in a url string

I'm trying to get the service password in a url stored in a table.
Example:
Parameters=http://google.com?ServiceUN=testUN&ServicePW=testPW&RequestType=testrequestType&MemberCode=TestMemberCode
This is where I'm at so far, the 9 in the substring function is only to use as a test length, that's the part I'm having issues with getting.
SELECT
SUBSTRING(Parameters,
CHARINDEX('ServicePW=', Parameters) + LEN('ServicePW='), 9)
FROM Table
WHERE TestID = 8
SELECT
substring(
Parameters,
charindex('ServicePW=', Parameters) + 10, -- len('ServicePW=')
charindex('&', substring(Parameters, charindex('ServicePW=', Parameters), len(Parameters))) - 11 -- (- len('ServicePW=') - 1)
)
FROM
Table
WHERE
TestID = 8
SELECT SUBSTRING(SUBSTRING(Parameters, PATINDEX('%ServicePW=%', Parameters), LEN(Parameters)), 11, PATINDEX('%&%', SUBSTRING(Parameters, PATINDEX('%ServicePW=%', Parameters), LEN(Parameters))) - 11)
FROM Table where TestID = 8

how to handle Zero divided by zero in sqlserver

how we can handle 0/0 in SQL Server? I used select nullif(0)/nullif(0) but ..
Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
Use NULLIF like this something like this
SELECT 0/NULLIF(0,0)
If you want the result as 0 when you encounter NULL, then use ISNULL/COALESCE
SELECT COALESCE(0/NULLIF(0,0),0)
In your query, you only need to move the ISNULL to check like this isnull(([Total Collection]) / nullif([Billed Amount], 0), 0)
update generalRegionWise set [Collection %] =
convert(VARCHAR,convert(MONEY,100.0 * isnull(([Total Collection]) / nullif([Billed Amount], 0), 0)),1) + '%'
It is recommended to specify the length when converting to VARCHAR like this convert(VARCHAR(50),... In your case it will take the default length of 30.
here are a few more examples.
DECLARE #numerator Int = 0
DECLARE #denominator Int = 0
SELECT ISNULL(NULLIF(#numerator, #denominator),0) AS Result;
SELECT CASE WHEN #denominator = 0
THEN 0
ELSE #numerator / #denominator
END AS Results
Hope this helps.

THROW with percentage sign (%) produces strange error message

Executing the following T-SQL statement in SSMS1 gives an error message that contains exactly one space2:
THROW 50000, 'abc%de', 0;
Msg 50000, Level 16, State 0, Line 1
However, if I escape % by doubling it, I get the expected error message:
THROW 50000, 'abc%%de', 0;
Msg 50000, Level 16, State 0, Line 1
abc%de
I also noticed that when % is followed by space, it is just skipped:
THROW 50000, 'abc% de', 0;
Msg 50000, Level 16, State 0, Line 1
abc de
For some reason, THROW is interpreting % in a special way.
Does anybody know why?
Are there any other "special" characters?
Is this documented anywhere?
I have observed this behavior under MS SQL Server 2012 and 2014. I haven't tried other versions.
1 I have also tried ADO.NET, with equivalent results.
2 This is not clearly visible here, but I have double-checked: the error message is indeed not an empty string, but exactly one space.
The documentation for THROW states:
The message parameter does not accept printf style formatting
https://msdn.microsoft.com/en-us/library/ee677615.aspx
That should explain why it fails to print the text.
There is more information about printf style formating in SQL Server in the RAISERROR documentation (msg_str):
https://msdn.microsoft.com/en-us/library/ms178592.aspx
This will test characters from 0-255 to check if they will return something:
DECLARE #errors TABLE(CharNumber INT, CharValue CHAR(1), ErrorText NVARCHAR(4000));
DECLARE #i INT = 0;
WHILE (#i <= 255)
BEGIN
DECLARE #c CHAR(1) = CHAR(#i);
DECLARE #m VARCHAR(50) = 'abc%' + #c + 'de';
BEGIN TRY
THROW 50000, #m, 0;
END TRY
BEGIN CATCH
INSERT INTO #errors
SELECT #i, #c, ERROR_MESSAGE();
END CATCH
SET #i = #i + 1;
END
SELECT * FROM #errors WHERE ErrorText > '' ORDER BY CharNumber
Output:
CharNumber CharValue ErrorText
32 abc de
33 ! abc!de
37 % abc%de
46 . abc.de
48 0 abcde
110 n abc
nde --<- This adds a new line.
%n = new line, but it do not remove n, that is a bit funny.

SQL Server Cast varchar column value '1218300.00' as int

A large value in a column has caused my SQL to throw error msg:
Error converting data type varchar to numeric
I have isolated this to a particular row. Here is a simplified script that "works":
SELECT
MtgeLoanAmount
, CAST(convert(numeric(15,2),'1218300.00') as int) as TrialValue
FROM dbo.Processed_VA_From_Excel
where FipsStateCode='06'
and FipsCountyCode='013'
and GuarantyAmount = '304575'
which returns results as pasted here:
So when I try to "generalize" my test by adding a 3rd column as follows it fails to convert:
SELECT
MtgeLoanAmount
, CAST(convert(numeric(15,2),'1218300.00') as int) as TrialValue
, CAST(convert(numeric(15,2),MtgeLoanAmount) as int)
FROM dbo.Processed_VA_From_Excel
where
FipsStateCode='06'
and FipsCountyCode='013'
and GuarantyAmount = '304575'
returns this:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
This may work for you:
SELECT
MtgeLoanAmount,
CONVERT(INT, ROUND(MtgeLoanAmount, 0)) AS MtgeLoanAmountNoCents
FROM
dbo.Processed_VA_From_Excel
WHERE
FipsStateCode = '06' AND
FipsCountyCode = '013' AND
GuarantyAmount = '304575'

Resources