Conversion failed when converting the nvarchar value to data type int sql server - sql

I have a table. There is data in this table and there is a checkbox next to each data. Multiple selection is possible. After the user makes a selection, the id numbers of the selected columns are come in the array. I convert the array to string and send it to the stored procedure and I run the following stored procedure:
Example value for #ResultsIds: 65, 66, 67, 68, 125
#ResultsIds nvarchar(250)
UPDATE MyTable SET [IsVerified] = 1 WHERE Id IN (#ResultsIds)
And I got this error:
Conversion failed when converting the nvarchar value '65, 66, 67, 68, 125' to data type int. Because [Id] column is int data type.
I tried CAST and CONVERT functions of SQL but it didn't work.

SQL Server doesn't do that automatically. Assuming you're on a recent version, you can do this:
declare #ResultsIds nvarchar(250) = '65,66,67,68,125'
UPDATE MyTable
SET [IsVerified] = 1
WHERE Id IN (
select [value]
from string_split(#ResultIDs, ',')
)

declare #ResultsIds nvarchar(250)='65,66,67,68,125'
UPDATE MyTable SET [IsVerified] = 1 WHERE cast(Id as varchar) IN (#ResultsIds)

I solved problem using foreach. I separated the numbers in the string from commas and transferred each number to the array. Then I updated the array one by one by running foreach loop.
public void Verify(DB db, string rows)
{
int[] nums = Array.ConvertAll(rows.Split(','), int.Parse);
foreach (int value in nums)
{
DbCommand cmd = db.GetStoredProcCommand("VerifyProcess");
db.AddInParameter(cmd, "#ResultId", DbType.Int32, value);
db.ExecuteNonQuery(cmd);
}
}

Related

Parse SQL Column into separate columns

I'm looking to parse a sql column result into separate columns. Here is an example of the column...
Detail - Column name
'TaxID changed from "111" to "333". Address1 changed from "542 Test St." to "333 Test St". State changed from "FL" to "DF". Zip changed from "11111" to "22222". Country changed from "US" to "MX". CurrencyCode changed from "usd" to "mxn". RFC Number changed from "" to "test". WarehouseID changed from "6" to "1". '
I need to take the old TAXID, new TAXID, old country, and new country and put them in separate columns.
The Detail column will always have TAXID and Country, however the challenging part is that they don't always have the rest of data that I listed above. Sometimes it will contain city and other times it won't. This means the order is always different.
I would create a tsql proc, use a case statement.
Do a count of the double quotes. If there are 8 oairs, you know that you old and new values, only 4 pairs you only have new values.
Then using the double quotes as indexes for your substring, you can put the vales into the table.
Good luck!
I was able to come up with something that worked.
In case anyone else gets a situation like this again perhaps posting my code will help.
DECLARE #document varchar(350);
set #document = 'TaxID changed from "111" to "222"'
declare #FIRSTQUOTE int
declare #SECONDQUOTE int
declare #OLDTAXID nvarchar(40)
declare #firstlength int
declare #ThirdQuote int
declare #FourthQuote int
declare #secondlength int
declare #NewTAXID nvarchar(40)
declare #oneplussecondquote int
declare #oneplusthirdquote int
select #FirstQuote = CHARINDEX('"',#document)
set #FIRSTQUOTE = #FIRSTQUOTE + 1
select #SECONDQUOTE = CHARINDEX('"',#document,#FIRSTQUOTE)
set #firstlength = #SECONDQUOTE - #FIRSTQUOTE
select #OLDTAXID = SUBSTRING(#document,#FIRSTQUOTE,#firstlength)
set #oneplussecondquote = #SECONDQUOTE + 1
select #ThirdQuote = CHARINDEX('"',#document,#oneplussecondquote)
set #oneplusthirdquote = #ThirdQuote + 1
select #FourthQuote = CHARINDEX('"',#document,#oneplusthirdquote)
select #secondlength = #FourthQuote - #oneplusthirdquote
select #NewTAXID = SUBSTRING(#document,#oneplusthirdquote,#secondlength)
You can switch out the string for this: 'Country changed from "US" to "MX"'
And it would grab the old country and new country

DB2: How to validate date in String format which is a varchar data type

I need to know wheather a data in a column of type varchar is in correct date format or not .
I have to do the same in DB2.
I have done this in java by using SimpleDateFormat() and Date.Parse() functions with the help of Exception handling .
I'm posting my java code to validate a string to date
private boolean isValidDate(String date) {
try{
DateFormat d = new SimpleDateFormat("yyyyMMdd");
d.setLenient(false);
d.parse(date);
return true;
}
catch(Exception e){
return false;
}
}
but now i have to do the same in DB2 data base.Can i use any functions or procederes in DB2
my data in table column is like this..
20140231
20000101
.
.
.
yyyyMMdd
and column type is varchar
My style of display the date:
try
{
Date dob = new SimpleDateFormat("yyyy-MMM-dd").parse(request.getParameter("date"));
user.setDate(date);
}
catch(ParseException e)
{
e.printStackTrace();
}
note: if you should give like as yyyy-MMM-dd or MM/dd/yyyy
your programs as:
private boolean isValidDate(String date)
{
try
{
DateFormat d = new SimpleDateFormat("MMM/dd/yyyy").parse(request.getParameter("date"));
d.setLenient(false);
d.parse(date);
return true;
}
catch(Exception e)
{
return false;
}
}
Timestamp to varchar:
timestamp-expression
An expression that returns a value that must be a DATE or TIMESTAMP, or a valid string representation of a date or timestamp that is not a CLOB or DBCLOB.
If the argument is a string, the format-string argument must also be specified.
In a Unicode database, if a supplied argument is a graphic string representation of a data, time, or timestamp, it is first converted to a character string before evaluating the function.
If timestamp-expression is a DATE or a valid string representation of a date, it is first converted to a TIMESTAMP(0) value, assuming a time of exactly midnight (00.00.00).
For the valid formats of string representations of datetime values, see "String representations of datetime values" in "Datetime values".
format-string
The expression must return a value that is a built-in CHAR, VARCHAR, numeric, or datetime data type.
If the value is not a CHAR or VARCHAR data type, it is implicitly cast to VARCHAR before evaluating the function.
In a Unicode database, if the supplied argument is a GRAPHIC or VARGRAPHIC data type, it is first converted to VARCHAR before evaluating the function. The actual length must not be greater than 254 bytes (SQLSTATE 22007).
The value is a template for how timestamp-expression is to be formatted.
A valid format-string must contain a combination of the format elements listed below (SQLSTATE 22007).
Two format elements can optionally be separated by one or more of the following separator characters:
minus sign (-)
period (.)
slash (/)
comma (,)
apostrophe (')
semi-colon (;)
colon (:)
blank ( )
note:
click 1
click2
UPDATE:
sample code 1: Convert the current date to YYYYMM format
SELECT DATE_FORMAT(NOW(), '%Y%m');
o/p: # 201403
sample code 2: Convert the current date to YYYYMM format
SELECT VARCHAR_FORMAT(CURRENT_DATE, 'YYYYMM') FROM jmail;
o/p # 201403
sample:
No | MySQL | DB2 |SampleOutput
1 | DATE_FORMAT(NOW(), '%Y-%m-%d) | VARCHAR_FORMAT(CURRENT_DATE,'YYYY-MM-DD')| 2013-02-14
2 | DATE_FORMAT(NOW(), '%d/%m/%y')| VARCHAR_FORMAT(CURRENT_DATE,'DD/MM/RR') | 14/02/13
It's not clear what "flavor" of DB2 is needed. With DB2 for i, I'd probably create a function to do the test and return an indication of success or failure. Here's an example that works for me:
DROP SPECIFIC FUNCTION SQLEXAMPLE.CHKVCDATE ;
SET PATH "QSYS","QSYS2","SYSPROC","SYSIBMADM","SQLEXAMPLE" ;
CREATE FUNCTION SQLEXAMPLE.CHKVCDATE (
VCDATE VARCHAR(20) )
RETURNS INTEGER
LANGUAGE SQL
SPECIFIC SQLEXAMPLE.CHKVCDATE
DETERMINISTIC
CONTAINS SQL
RETURNS NULL ON NULL INPUT
NO EXTERNAL ACTION
NOT FENCED
SET OPTION ALWBLK = *ALLREAD ,
ALWCPYDTA = *OPTIMIZE ,
COMMIT = *CHG ,
CLOSQLCSR = *ENDMOD ,
DECRESULT = (31, 31, 00) ,
DFTRDBCOL = *NONE ,
DYNDFTCOL = *NO ,
DYNUSRPRF = *USER ,
SRTSEQ = *HEX
BEGIN ATOMIC
DECLARE CHKDATE DATE ;
DECLARE VALIDDATE INT ;
DECLARE NOT_VALID CONDITION FOR '22007' ;
DECLARE CONTINUE HANDLER FOR NOT_VALID
SET VALIDDATE = -1 ;
SET VALIDDATE = 0 ;
VALUES ( VCDATE ) INTO CHKDATE ;
RETURN VALIDDATE ;
END ;
COMMENT ON SPECIFIC FUNCTION SQLEXAMPLE.CHKVCDATE
IS 'Check VARCHAR for valid date' ;
Any properties or other details that don't fit your particular DB2 can be removed or changed. The size of the VCDATE VARCHAR parm might need adjustment, and the RETURN value can be whatever you need. The function might be useful in a WHERE clause.
I can invoke it like this:
select sqlexample.chkvcdate('2014-02-29'), sqlexample.chkvcdate('2014-02-28') from sysibm.sysdummy1
The first will return ( -1 ) for the invalid value, and the second will return ( 0 ) for valid.

Using newline character and adding several rows of strings into one

I have in my hands an old app on informix server and I'm migrating data into a different database. Both are informix databases. I have a particular problem with one table. Old app used it to support multiline text.
OldTable:
HeaderID int
LineNum int
Descr nvarchar(50,1)
NewTable:
HeaderID int
Descr lvarchar(max)
So, for each HeaderID I have to read the descriptions ordered by line number and put them all together for insert into a new table. There has to be a newline character between each line for conversion to succeed.
Any tips on how to do this?
If you need to do it from SQL then you can use procedure:
CREATE FUNCTION get_text(aHeaderID int)
RETURNING lvarchar;
DEFINE result lvarchar;
DEFINE vcfld lvarchar;
LET result=NULL;
EXECUTE PROCEDURE IFX_ALLOW_NEWLINE('T');
FOREACH cur1
FOR SELECT Descr INTO vcfld FROM OldTable WHERE HeaderID = aHeaderID ORDER BY LineNum
IF result IS NULL THEN
LET result = vcfld;
ELSE
LET result = result || '
' || vcfld;
END IF;
END FOREACH;
RETURN result;
END FUNCTION;
(notice usage of IFX_ALLOW_NEWLINE and line breaking when updating result)
Then you can fill NewTable using:
UPDATE NewTable SET Descr=get_text(HeaderID);
You can use PreparedStatement. This is example in Jython that uses JDBC Informix driver:
db = DriverManager.getConnection(db_url, usr, passwd)
pstm = db.prepareStatement("SELECT vc FROM src ORDER BY id")
rs = pstm.executeQuery()
lines = []
while (rs.next()):
lines.append(rs.getString(1))
pstm = db.prepareStatement("INSERT INTO dest (lvc) VALUES (?)")
pstm.setString(1, '\n'.join(lines))
rs = pstm.execute()
db.close()

SQL Replace and where CAST(PromotionRuleData as NVARCHAR(MAX))

Can't seem to edit my old post but I am trying to execute this SQL script
UPDATE Promotions
set Description = '£5 Off £25 Spend',
UsageText = '£5 Off £25 Spend',
EmailText = '£5 Off £25 Spend',
PromotionRuleData= '<ArrayOfPromotionRuleBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionRuleBase xsi:type="StartDatePromotionRule"><StartDate>2013-11-18T00:00:00</StartDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationDatePromotionRule"><ExpirationDate>2014-01-13T00:00:00</ExpirationDate></PromotionRuleBase><PromotionRuleBase xsi:type="ExpirationNumberOfUsesPerCustomerPromotionRule"><NumberOfUsesAllowed>1</NumberOfUsesAllowed> </PromotionRuleBase><PromotionRuleBase xsi:type="MinimumCartAmountPromotionRule"><CartAmount>24.99</CartAmount></PromotionRuleBase></ArrayOfPromotionRuleBase>',
PromotionDiscountData = '<ArrayOfPromotionDiscountBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PromotionDiscountBase xsi:type="OrderPromotionDiscount"><DiscountType>Fixed</DiscountType><DiscountAmount>5.00</DiscountAmount></PromotionDiscountBase></ArrayOfPromotionDiscountBase>'
where Name = 'test1,test2,etc...'
It comes back with this error
Msg 402, Level 16, State 1, Line 1
The data types varchar and text are incompatible in the equal to operator.
I try to use where CAST(PromotionRuleData as NVARCHAR(MAX))
So the line reads as
CAST(PromotionRuleData as NVARCHAR(MAX)) = '<ArrayOfPromotionRuleBase ...
but no luck.
You cannot compare a string literal against a text column in SQL Server.
Which column is of datatype text ? Your name column that you use in the WHERE clause by any chance?
If so, use this WHERE instead:
WHERE CAST(Name AS VARCHAR(MAX)) = 'test1,test2,etc...'
or better yet: convert your column to a more appropriate datatype like VARCHAR(n) (unless you really need 2 GB = 2 billion characters - if so, then use VARCHAR(MAX))

Calling a stored procedure in SQL Server to get a unicode string

I'm trying to get a name by calling a stored procedure.
sql code:
create procedure GetName
#ID int,
#name nvarchar(32) output
as
select #name=name from SalesInfo where ID=#ID
c code
...
SQLRETURN rc;
SQLLEN cbParam = SQL_NTS;
int ID = 1;
wchar_t name[32];
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &ID, 0, NULL);
rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT_OUTPUT, SQL_C_WCHAR, SQL_WCHAR, SQL_DESC_LENGTH, 0, name, sizeof(name), &cbParam);
rc = SQLExecDirect(hstmt, TEXT("{call GetName(?,?)}"), SQL_NTS);
I received a string, but there was an error message, 'string data, right truncation'
The string was padded with blanks, like "name "
you need to increase the size of your nvarchar() so that it doesn't truncate the strings that are larger than 32
increase the size of wchar_t name[N];and #name nvarchar(N) output
Well to get rid of the trim simply use RTRIM(col) AS [col], to determin what length of char vars you need then LEN(Originalcol) or DATALENGTH(Originalcol) http://msdn.microsoft.com/en-us/library/ms173486.aspx in your case to create a proc to see waht actual length you are getting and what you need to define. As its a single var, you wont get much a hit by using NVARCHAR(MAX)