SQL: String match and lookup - sql

I have the following problem where the error data on a SQL table is very specific:
Now this is just a sample error set and I would like to consolidate these errors into a single error set. For instance, the error "The date year on policy found does not match the request" needs to be aggregate into a single error code such as "DATE_YEAR_MISMATCH" or whatever message. Likewise, the error code "No results found for PolicyId..." needs to be aggreagated.
My Attempt:
So I wanted to build a calculated column and a lookup table. For instance, I created an error lookup table like this:
Create Table Lookup_ErrorCode
(
ErrorMessage Varchar(100),
ErrorCode Varchar(100)
)
Insert into Lookup_ErrorCode values('Invalid Login for Carrier', 'INVALID_LOGIN')
Insert into Lookup_ErrorCode values('Error getting data for Policy', 'ERROR_DATA_POLICY')
Insert into Lookup_ErrorCode values('The date year on policy found does not match the request', 'POLICY_DATE_MISMATCH')
Insert into Lookup_ErrorCode values('Error on Policy Effective Date. Policy', 'ERROR_POLICY_EFFECTIVE_DATE')
Insert into Lookup_ErrorCode values('No results found for PolicyId', 'NO_RESULTS_FOR_POLICY')
Insert into Lookup_ErrorCode values('Cannot find loan info though payor is set to mortgagee', 'LOAN_NOT_FOUND')
Insert into Lookup_ErrorCode values('No matching dates were found.', 'MATCHING_DATES_NOT_FOUND')
Now I created a user-defined function that can be used in my calculated column like this:
Create function CodeErrorMessage(#ErrorMessage varchar(max))
Returns VARCHAR(100)
AS
BEGIN
--Declare #ErrorMessage VARCHAR(max) = 'Invalid Login for Carrier: Universal Property & Casualty';
SELECT ErrorCode from Lookup_ErrorCode where [ErrorMessage] like LEFT(#ErrorMessage, 15)+'%'
Return 0;
END
However, there are some issues with this function because when I use a Left function taking in only 15 characters, it causes issues with some of the other error messages. What would be the best way to do a complete string match with the lookup and eliminating some redundant info such as policy number or effective in the search? Any help would be greatly appreciated.

try the syntax changings as following
SELECT LEFT(#ErrorMessage, 15) from Lookup_ErrorCode where [ErrorMessage] like '%' + #ErrorCode + '%'
Hope this will work fine for you

Related

How to find which field is giving data type error in QUERY

I have the query report for user but have some error message display:
Error converting data type nvarchar to bigint
only one message.
How to find which field is giving data type error in query? Anyone can give advice? Many thanks!
As you have not provided data, it looks like you have NVARCHAR datatype, which is not implicitly convertable to Bigint
SELECT CAST(N'287888' AS BIGINT) -- Success
SELECT CAST(N'ABC123' AS BIGINT) -- Failure
See which column is failing and accordingly fix it.
You can either only load the proper values:
SELECT * FROM Table WHERE TRY_CAST(ErrorField AS BIGINT) IS NOT NULL
Or, You can load them as NULL(provided the target column allows NULL)
SELECT TRY_CAST(ErrorField AS BIGINT) FROM Table

SQL Server. Allow multiple values throwing error Conversion failed when converting the nvarchar value … to data type int

Newbie here. Attempting to allow report to run multiple values when being run but above error happens when selecting multiple. Any help will be appreciated.
where ContactActivityNoteType.ClientId = 1
and ContactActivityNoteType.ContactActivityNoteTypeId in (13, 4, 22)
and tc.ContactTypeId = 2
and ca.EnteredOn between #start_date and #end_date
and ca.ClientAccountId in (#ClientAccountId)
One option is to change your multi-valued parameter to a temporary table and then join that temp table to your main table.
In your query based dataset, you can do this part before main query.
For example, if following is your multi-valued variable:
DECLARE #ClientAccountId VARCHAR(MAX) = 'a10001,a10002,a10003,a10004'
You can use the following chunk of SQL code to change it to a temp table:
CREATE TABLE #ClientAccountIds (ClientAccountId VARCHAR(30));
DECLARE #Insert VARCHAR(MAX) = 'INSERT INTO #ClientAccountIds VALUES ('''+REPLACE(#ClientAccountId,',','''),(''')+''');';
EXEC (#Insert);
So that following SQL:
SELECT ClientAccountId FROM #ClientAccountIds
will return:
And now you can easily join this temporary table to your main query.
Hope this help?

DB2 Query Token SMALLINT was not valid

Forum.
I am working with IBM System i Version 7.1.
I am having issues in the source code with the following merge statement so I copied it over to the database client to utilize the "Run SQL Scripts" functionality.
Rather than replacing the coded in #Variables in the statement I wanted to declare local variables so that I could test the statement as is.
The added the following 'declare and set' lines and I get the following error:
declare #groupId smallint
set #groupId = 99
declare #groupName varchar(40)
set #groupName = 'Sam'
declare #groupId smallint
SQL State: 42601
Vendor Code: -104
Message: [SQL0104] Token SMALLINT was not valid. Valid tokens: DYNAMIC SENSITIVE ASENSITIVE INSENSITIVE. Cause . . . . . : A syntax
error was detected at token SMALLINT. Token SMALLINT is not a valid
token. A partial list of valid tokens is DYNAMIC SENSITIVE ASENSITIVE
INSENSITIVE. This list assumes that the statement is correct up to
the token. The error may be earlier in the statement, but the syntax
of the statement appears to be valid up to this point. Recovery . . .
: Do one or more of the following and try the request again: --
Verify the SQL statement in the area of the token SMALLINT. Correct
the statement. The error could be a missing comma or quotation mark,
it could be a misspelled word, or it could be related to the order of
clauses. -- If the error token is , correct the SQL
statement because it does not end with a valid clause.
Processing ended because the highlighted statement did not complete >successfully
I have tried adding semicolons to the end of each line and begin and end statements and still no success.
Below is the whole statement I am trying to execute:
declare #groupId smallint
set #groupId = 99
declare #groupName varchar(40)
set #groupName = 'Sam'
merge into database.table as t
using ( values( cast(#groupId as smallint)
,cast(#groupName as varchar(40))
))
as caz( group_id
, group_name
)
on t.group_id = caz.group_id
when matched then update
set t.group_name = caz.group_name
when not matched then
insert ( group_id
, group_name
)
values (caz.group_id
, caz.group_name
);
Any help is appreciated.
Please let me know if I may provide anymore information.
I may have found an answer here: https://stackoverflow.com/a/4451159/2272357
CREATE OR REPLACE VARIABLE variableName VARCHAR(50);
SET variableName = 'blah';
SELECT * FROM table WHERE column = variableName;
DROP VARIABLE variableName;
I have yet to verify it works successfully. I believe it may be a local issue though.

MonetDB Prepare Statement in Function

I'm trying to create a function that takes the parameters for the column, the table, the limit, and offset. Basically, I want to be able to get a specified number of rows data from a specified table from a specified column.
However, I'm unable to get the following code to work - I get several errors such as:
syntax error, unexpected SELECT, expecting ':' in: "create function get_banana(lim int, off int, tbl varchar(32), col varchar(32)) r"
syntax error, unexpected RETURN in: "return"
syntax error, unexpected END in: "end"
These errors seem kind of meaningless.
My code is as follows:
CREATE FUNCTION GET_BANANA(lim int, off int, tbl varchar(32), col varchar(32))
RETURNS TABLE (clm int)
BEGIN
PREPARE SELECT col FROM tbl LIMIT ? OFFSET ?;
RETURN EXEC (lim, off);
END;
I'd appreciate any help :) Thanks!
I see at least two issues
EXEC needs the identifier that is returned by PREPARE, e.g.:
sql>prepare select * from tables;
execute prepared statement using: EXEC 2(...)
sql>exec 2();
The function parameters tbl and col are string values. You cannot use them as table/column identifiers.
Having said that, I am not even sure if PREPARE can be used inside a function.
No, PREPARE is a top-level statement modifier.

T-SQL find an eight character string which contains no spaces and at least 1 number from within a string and exclude it

The problem is we have many different error messages being produced and stored in a sql table
within the error message there could be an occurance of a project number 8 characters long
which would contain at least 1 number is alphanumeric and no spaces. per error message the project number may not be the same.
e.g.
'error found processing project: abcd12sf no funding is set'
'error found processing project: qd451srf no funding is set'
'error project 2344ddrf has no approver'
We want to be able to count the occurances of particular errors and so we need to strip the project number from the output
thus
'error found processing project: no funding is set' , 2 occurances
'error project has no approver' , 1 occurance
Any help is greatly appreciated
Start by creating a Function that returns the project number. I did this by finding the first integer and then position of the space after it, then counting back 8 characters you have the start and end position.
CREATE FUNCTION GetProjectNumber(#FullErrorMessage varchar(100))
RETURNS CHAR(8)
AS
BEGIN
DECLARE #ProjectNumber CHAR(8)
SET #ProjectNumber = (
SELECT
SUBSTRING(#FullErrorMessage, CHARINDEX(' ',#FullErrorMessage,PATINDEX('%[0-9]%',#FullErrorMessage))-8,8)
)
RETURN #ProjectNumber
END
Alter your table to have a computed column called ProjectNumber here is the create I did for testing but you should get the idea.
CREATE TABLE T_Errors(
ID int IDENTITY(1,1),
ErrorMessage varchar(1024),
ProjectNumber AS (dbo.GetProjectNumber(ErrorMessage))
CONSTRAINT PK_T_Errors PRIMARY KEY CLUSTERED(ID))
Now you have the project number in a separate column it is easy to play with.
SELECT
CleanErrorMessage = REPLACE(ErrorMessage,ProjectNumber,''),
COUNT(*) As ErrorCount
FROM T_Errors
GROUP BY REPLACE(ErrorMessage,ProjectNumber,'')
If you have a list of valid project numbers you can do something like this.
Sample tables and data:
declare #Project table
(
ProjectNumber char(8)
)
insert into #Project values
('abcd12sf'),
('qd451srf'),
('2344ddrf')
declare #Error table
(
Error varchar(100)
)
insert into #Error values
('error found processing project: abcd12sf no funding is set'),
('error found processing project: qd451srf no funding is set'),
('error project 2344ddrf has no approver')
The query:
select P.Error,
count(*) as ErrorCount
from #Error as E
cross apply
(
select replace(E.Error, P.ProjectNumber, '') as Error
from #Project as P
where E.Error like '%'+P.ProjectNumber+'%'
) as P
group by P.Error
Result:
Error ErrorCount
-------------------------------------------------- ----------
error found processing project: no funding is set 2
error project has no approver 1