DB2 Query Token SMALLINT was not valid - sql

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.

Related

SQL: String match and lookup

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

Unpredictable behaviour in nested CASE statement

I'm unable to figure out why the control goes always to a statement irrespective of inside CASE condition.
A normal SQL statement works, but with my table it does not work.
--Not working--
SELECT
CASE WHEN [INTERNALDESCRIPTION] IS NOT NULL THEN --INTERNALDESCRIPTION IS A TEXT FIELD
CASE WHEN 'INT' = 'INT' THEN -- Or 'TEXT' = 'INT'
REPLACE( CONVERT(VARCHAR(MAX),[INTERNALDESCRIPTION] ) ,'''','') --should have come here
ELSE
REPLACE( CONVERT(INT,[INTERNALDESCRIPTION] ) ,'''','' ) -- Always comes here no matter what condition
END
ELSE
'NULL'
END
FROM DBO.RESOURCESTRINGMASTER WITH(NOLOCK) WHERE 1=1
-------working--
DECLARE #VALUE1 AS varchar(max) = '1Test', #VALUE2 AS VARCHAR(MAX) = '2'
SELECT
CASE WHEN #VALUE1 IS NOT NULL THEN
CASE WHEN 'INT' = 'INT' THEN
REPLACE( CONVERT(VARCHAR(MAX),#VALUE1 ) ,'''','')
ELSE
REPLACE( CONVERT(INT,#VALUE2 ) ,'''','' )
END
ELSE
'NULL'
END
And results in below error:
Explicit conversion from data type text to int is not allowed.
Explicit conversion from data type text to int is not allowed.
This error message seems pretty clear. Why are you using a text data type? It is deprecated. To quote from the documentation:
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
So, your code on the real table is executing the ELSE condition, which causes it to fail. In the code with constants, ELSE condition is not failing. Why is this?
I think the error is being caught in the compilation phase of the query. The error does not occur in the second example, because SQL Server is short-circuiting the query, recognizing that the ELSE is not needed. The code in the second example is simply not compiled.
I am pretty sure you would see the same behavior if you replaced the code with 1 / 0 (although the other part of the case expression would need to change as well for the types to be compatible).
It is not running the statement, it is failing because it sees something illegal.
If you want to see it on the other case change this line
DECLARE #VALUE1 AS varchar(max) = '1Test', #VALUE2 AS VARCHAR(MAX) = '2'
to
DECLARE #VALUE1 AS TEXT = '1Test', #VALUE2 AS VARCHAR(MAX) = '2'
You are comparing different test cases -- the first is not using VARCHAR

Must declare the scalar variable with SELECT statement

I have the following statement:
DECLARE #Nr_Karton int;
SELECT #Nr_Karton = ISNULL(MAX(Nr), 1000) FROM W_Karton;
SET #Nr_Karton = #Nr_Karton + 1;
INSERT INTO W_Karton (Container_ID, Nr, Beschrieb, CreationDate, Location)
VALUES ('1', #Nr_Karton, '', getDate(), 'Bösingen');
But I get the error:
[SQL] SELECT #Nr_Karton = ISNULL(MAX(Nr), 1000) FROM W_Karton
[Err] 42000 - [SQL Server]Must declare the scalar variable "#Nr_Karton".
How to get rid of the error?
I did some playing with this. The fictional schema I created was:
CREATE TABLE W_Karton (Container_ID int, Nr int, Beschrieb varchar(1),
CreationDate datetime, Location varchar(10))
Whilst it parsed and ran fine on my local 2008R2 box, the same code did not work when pasted into a SQL Fiddle.
However, if you remove all the semi-colons apart from the last one as per this SQL Fiddle you can see it seems to work fine!
I believe it shouldn't make any difference, but if you would rather it worked and don't care about the why, give it a try...
I encountered the same issue. It turns out it is due to ';' being selected as the "Query Terminator". IN SQL Fiddle, this actually means "batch terminator". There should be a drop-down button on the bottom right that has the text "[;]". Click that and select "Keyword [GO]".

How to pass multiple values to single parameter in stored procedure

I'm using SSRS for reporting and executing a stored procedure to generate the data for my reports
DECLARE #return_value int
EXEC #return_value = [dbo].[MYREPORT]
#ComparePeriod = 'Daily',
#OverrideCompareDate = NULL,
#PortfolioId = '5,6',
#OverrideStartDate = NULL,
#NewPositionsOnly = NULL,
#SourceID = 13
SELECT 'Return Value' = #return_value
GO
In the above when I passed #PortfolioId = '5,6' it is giving me wrong inputs
I need all records for portfolio id 5 and 6 also is this correct way to send the multiple values ?
When I execute my reports only giving #PortfolioId = '5' it is giving me 120 records
and when I execute it by giving #PortfolioId = '6' it is giving me 70 records
So when I will give #PortfolioId = '5,6' it should have to give me only 190 records altogether, but it is giving me more no of records I don't understand where I exactly go wrong .
Could anyone help me?
thanks
all code is too huge to paste , i'm pasting relevant code please suggest clue.
CREATE PROCEDURE [dbo].[GENERATE_REPORT]
(
#ComparePeriod VARCHAR(10),
#OverrideCompareDate DATETIME,
#PortfolioId VARCHAR(50) = '2', --this must be multiple
#OverrideStartDate DATETIME = NULL,
#NewPositionsOnly BIT = 0,
#SourceID INT = NULL
) AS
BEGIN
SELECT
Position.Date,
Position.SecurityId,
Position.Level1Industry,
Position.MoodyFacilityRating,
Position.SPFacilityRating,
Position.CompositeFacilityRating,
Position.SecurityType,
Position.FacilityType,
Position.Position
FROM
Fireball_Reporting.dbo.Reporting_DailyNAV_Pricing POSITION WITH (NOLOCK, READUNCOMMITTED)
LEFT JOIN Fireball.dbo.AdditionalSecurityPrice ClosingPrice WITH (NOLOCK, READUNCOMMITTED) ON
ClosingPrice.SecurityID = Position.PricingSecurityID AND
ClosingPrice.Date = Position.Date AND
ClosingPrice.SecurityPriceSourceID = #SourceID AND
ClosingPrice.PortfolioID IN (
SELECT
PARAM
FROM
Fireball_Reporting.dbo.ParseMultiValuedParameter(#PortfolioId, ',') )
This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.
Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:
CREATE TABLE #TempTable (ID INT)
WHILE LEN(#PortfolioID) > 0
BEGIN
IF NOT <#PortfolioID contains Comma>
BEGIN
INSERT INTO #TempTable VALUES CAST(#PortfolioID as INT)
SET #PortfolioID = ''
END ELSE
BEGIN
INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
SET #PortfolioID = <Everything after the next comma>
END
END
Then, change your condition to
WHERE PortfolioId IN (SELECT ID FROM #TempTable)
EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:
You can define a multivalue parameter for any report parameter that
you create. However, if you want to pass multiple parameter values
back to a data source by using the query, the following requirements
must be satisfied:
The data source must be SQL Server, Oracle, Analysis Services, SAP BI
NetWeaver, or Hyperion Essbase.
The data source cannot be a stored procedure. Reporting Services does
not support passing a multivalue parameter array to a stored
procedure.
The query must use an IN clause to specify the parameter.
This I found here.
I spent time finding a proper way. This may be useful for others.
Create a UDF and refer in the query -
http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm
USE THIS
I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.
http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/
I hope this helps people because it was exactly what I was looking for
Either use a User Defined Table
Or you can use CSV by defining your own CSV function as per This Post.
I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.
Cheers!
I think, below procedure help you to what you are looking for.
CREATE PROCEDURE [dbo].[FindEmployeeRecord]
#EmployeeID nvarchar(Max)
AS
BEGIN
DECLARE #sqLQuery VARCHAR(MAX)
Declare #AnswersTempTable Table
(
EmpId int,
EmployeeName nvarchar (250),
EmployeeAddress nvarchar (250),
PostalCode nvarchar (50),
TelephoneNo nvarchar (50),
Email nvarchar (250),
status nvarchar (50),
Sex nvarchar (50)
)
Set #sqlQuery =
'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
from Employee e
join EmployeeDetail ed on e.Empid = ed.iEmpID
where Convert(nvarchar(Max),e.EmpId) in ('+#EmployeeId+')
order by EmpId'
Insert into #AnswersTempTable
exec (#sqlQuery)
select * from #AnswersTempTable
END

SQL Error Alter Table?

I have been trying to add columns to a table using some logic that produces this statement:
ALTER TABLE Master_List
ADD COLUMN Service VARCHAR(100) ,
Vendor VARCHAR(100) ,
Product VARCHAR(100) ,
Service_Description VARCHAR(100) ,
Level/Scale VARCHAR(100) ,
SunGard_Contract_Schedule_ID VARCHAR(100) ,
Application_Owner VARCHAR(100) ,
Application_Servers VARCHAR(100) ,
Required_Support/Dependencies VARCHAR(100);
whenever I have been trying to run it I continually get this error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
at Testing.main(Testing.java:54)
I have been checking online for the proper format for the ALTER TABLE command, and the formatting seems to be correct, I have tried changing so many things I have run out of ideas of how to fix it....
The table name is Master_List, and none of those columns already exist inside it.
This is being used inside Java, incase that is relevant.
It could be the / in your column names that is giving you the problem
Your column names contain the "/" character, and that is not a valid character for column names.