How to increment varchar value like AEC00001 - c#

i have to increment a string value by 1, like default value will be AEC00001 and second value will be AEC00002 and so on, how can i achieve this by using c# or sql query.

It looks like a bad design somewhere in your application. Probably you should store number and prefix separately.
But anyway, assuming your prefix is always "AEC" and size of number is five decimal places - you can increment your values like (this is c# solution since you haven't specified if you prefer sql solution to c# one):
string s = "AEC00001";
string s1 = "AEC" +
(Convert.ToInt32(s.Replace("AEC", "")) + 1)
.ToString()
.PadLeft(5, '0');

You cant store 0000 before number in INT format, but you can do something like that:
SELECT RIGHT('0000' + CAST(2 AS varchar(5)) , 5)
OR
SELECT '0000' + CAST(2 AS varchar(5))

Here I used computed column which automatically takes other column and con-cats to it
declare #a table ( a as 'AEC'+b, b nvarchar(max))
insert into #a SELECT RIGHT('00000'+CAST(1 AS VARCHAR(5)),5)union select RIGHT('00000'+CAST(2 AS VARCHAR(5)),5) union select RIGHT('00000'+CAST(3 AS VARCHAR(5)),5)
select * from #a

var originalValue = "AEC00002";
// Get the numeric part (00002)
var stringValue = Regex.Match(originalValue, #"\d+").Value;
// Convert to int
var intValue = Int32.Parse(stringValue);
// Increase
intValue++;
// Convert back to string
originalValue = "AEC" + intValue.ToString("D5");
Result: AEC00003

You may use a computed column:
A computed column is a column that expresses the data that can be used by an other column in the same table. This expression can be non-computed columns or any function and constant. It cannot be a sub-query. Here the computed column is marked as Persisted, so that any update made in the referenced column will be automatically synchronized in the computed column.
For more information, see this article: Auto Incremented Column With VARCHAR and NVARCHAR Data Type in SQL

In JavaScript Use the below function
function autoIncrementCustomId(lastRecordId){
let increasedNum = Number(lastRecordId.replace('ABC','')) + 1;
let kmsStr = lastRecordId.substr(0,3);
for(let i=0; i< 6 - increasedNum.toString().length; i++){
kmsStr = kmsStr+'0';
}
kmsStr = kmsStr + increasedNum.toString();
console.log(kmsStr);
}
autoIncrementCustomId('ABC009999')

Related

Check string value from database

I am haveing strange issue comparing string value. I have a value in SQL with type (nchar) this value equals "text". And I set this value to string variable x, after that I compared the string variable x with the word "text" .
The problem is it shows that x doesn't equal the value "text" even that when I add x value to label, it shows the word "text".
Here is my code:
string x;
using (SqlCommand cmd = new SqlCommand(
"select column from text_table where column = 'text'", sqlCon))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
x = reader["column"].ToString();
if (x.Equals("text"))
{
// run code
}
else
{
label1.Text ="x doesn't equal text";
}
when I use the code it always shos the message "x doesn't equal text" but it should run the code as the value of the string x is "text"
You have used the "nchar" column type, which has a constant length. I am not sure, but trimming before comparison may solve your problem.
Try
x = reader["column"].ToString().Trim();
Also there is a Bug, I think: There is no "x" here in (if (stat.Equals("text")).
Demo:
create table text_table (
col1 nchar(10) ); -- fixed length column
insert text_table(col1) values ('text');
Pay attention to col1+'1' expression
select col1, col1+'1'
from text_table
where col1 = 'text'
What is going on? sql-server really ignores trailing spaces e.g.
select 'OK' where 'text' = 'text ';
returns 'OK'.
But c# doesn't ignore trailing spaces and your if is not true.
What to do?
Use Nvarchar in your db or trim db column with String.Trim() before comparison.
Always use the .Equals() method with StringComparison.OrdinalIgnoreCase
Change your code to
if(x.Equals("text",StringComparison.OrdinalIgnoreCase){
//Do something
}

C#: How to add formula to Excel through C# Code. Getting invalid Formula error

Column 'I' have To date
Column 'H' have From date
I want to calculate difference between two date and store it in column 'J'.
Formula to do this is "=DATEDIF(I18,H18,"d")"
I am getting below error if i execute below code.
Error: Invalid formula.
ArgumentException was unhandled by user code.
private void FillExcelCellFormula(IRange cell, int row, int column, object content)
{
string row1 = "I" + Convert.ToString(row);
string row2 = "H" + Convert.ToString(row);
string dquote = #"""d""";
string daysFormula = "=DATEDIF(" + row1 + "," + row2 + "," + dquote + ")";
cell.FormulaR1C1 = daysFormula;
}
Formula value getting poppulated in daysFormula = "=DATEDIF(I18,H18,\"d\")"
Although i am not sure if the '\' is the reason behind the error.
Even a simple sum function is not working. I replaced the formula to a simpler formula like,
string daysFormula = "=SUM(A18:B18)";
yet i am getting same error.
Do i have to call for any library?
Any suggestions?
I would recommend checking the To & From dates.
What format are they stored in, in your Excel file ?
If they are stored as string, this might cause the error. Dates need to be stored as integers, with styling applying to display them as dates.
Update
Btw, dumb question: What happens if you use Formula rather than FormulaR1C1:
cell.Formula = daysFormula;

"Error converting" numeric input to correct TSQL type (possible Bug)

As of now I am encountering this kind of bug
Error converting data type float to decimal.
or
Error converting data type Numeric to decimal
This is my code
using (SqlConnection reportsConn = new SqlConnection(sqlConnWriter))
{
reportsConn.Open();
SqlCommand AddReconItem = new SqlCommand();
AddReconItem.Connection = reportsConn;
AddReconItem.CommandType = CommandType.StoredProcedure;
AddReconItem.CommandText = "Updater.usp_AddReconcileItems";
// AddReconItem.Parameters.Add("#varible",SqlDbType.Decimal
AddReconItem.Parameters.AddWithValue("#ITEMWEIGHT", Math.Round(Convert.ToDouble(WeightTextBox.Text+".00"), 2));
AddReconItem.Parameters.AddWithValue("#ITEMPRINCIPALAMT", Math.Round(Convert.ToDouble(PrincipalTexAmTextBox.Text + ".00"), 2));
AddReconItem.Parameters.AddWithValue("#FORLOANMONTH", Convert.ToDateTime(YearDropDownList.SelectedValue + "/" + MonthDropDownList.SelectedValue));
AddReconItem.Parameters.AddWithValue("#STORAGEGROUPID", StorageNameDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#BRANCHCODE",BranchCodeTextBox.Text);
AddReconItem.Parameters.AddWithValue("RECONID", ReconTypeDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#PAWNTIX",PwnTicketTextBox.Text);
AddReconItem.Parameters.AddWithValue("#CREATEDBY", Session["UserID"].ToString());
AddReconItem.ExecuteNonQuery();
}
When I input, 123 for principalamt and itemweight it accepts the answer and treats it as a decimal, but when I input 1234 for itemweight and still 123 for Principalamt it shows that error, if I remove the conversion and change it to Convert.ToDecimal it shows Error converting data type Numeric to decimal if I use it as text it shows Error converting data type varchar to decimal
Is this a bug or something? I can't seem to find a way I tried many options but none of them have been working
My database columns are below:
I really hope you can help me understand this phenomenon
EDIT
This is the first time I saw a program accepting 123 as a valid input while 1234 is not, my database Decimal (38,6) is very large enough to accommodate this input that's why I'm looking for the answer or known bugs that can solve this problem, thank you.
I'd suggest using Decimal.TryParse instead of Convert for your principalamt value and then maybe debugging and inspecting how the value gets converted to a valid Decimal for your Money column. For example something like;
bool valid;
var dbl = Convert.ToDouble("1234.00");
valid = Double.TryParse("1234.00", out dbl);
var dcml = Convert.ToDecimal("1234.00");
valid = Decimal.TryParse("1234.00", out dcml);
I'm not sure if you should be using Double as a data type when trying to store the resultant value in a Decimal field. Double represents floating type numbers and I think you should be using the Decimal data type for your Money column as mentioned in this answer.
For ItemWeight, with a data type of decimal(38,6), you'll end up with 6 decimal places regardless of your rounding I think. Try the following in SQL Server and make sure the parameter type for #ITEMPRINCIPALAMT is DECIMAL as well (similar to my example below).
DECLARE #Var decimal(38,6) = 1234.00
DECLARE #Tbl AS TABLE
(
Test decimal(38,6)
)
INSERT INTO #Tbl (Test) Values (#Var)
SELECT * FROM #Tbl

convert a double with a comma to a variable with a point to use in sql statement

I use my double in a select statement:
code:
SqlCommand command = new SqlCommand("SELECT min(Score) FROM "+ table +" WHERE [" + sportEvent + "] < (#result);", connect);
command.Parameters.AddWithValue("#result", result);
everything works fine if double result is an integer but not if result is a comma number (example 11,34) --> it should be 11.34 to work (point instead of comma)
How can I change a double 11,34 into 11.34 ?
It appears that your code sets a string parameter as a constraint for a DB value of numeric type, letting the database do the conversion. This is not a good idea, because it takes control away from your program: should DBA decide to reconfigure your backend database to "understand" commas instead of dots, your program will stop working!
Currently, your double is in a locale-specific format. You need to parse it using the locale-specific format provider, and then set the value that you get back from the parser as the parameter of your SQL query. Assuming that the current culture is one that is using commas as decimal separator, you can do this:
command.Parameters.AddWithValue(
"#result"
, double.Parse(s, CultureInfo.CurrentCulture)
);
You can use this
result.ToString(CultureInfo.InvariantCulture)
You could try changing the variable into string:
result.ToString().Replace(',','.');
This will replace the comma with a dot.
If result is Double then:
command.Parameters.Add("#result", SqlDbType.Float).Value = result

Adding two values from database together

How would i be able to add 2 parameter together?
i have this following code but it dont seem to work
balanceDB = readdata[("balance"+"overdraftLimit")].ToString();
balanceDB = (readdata["balance"] + readdata["overdraftlimit"]).ToString();
This is assuming that you will do the casts. If you don't have casts in your code you need to do something like:
balanceDB = (Convert.ToDouble(readdata["balance"].ToString()) + Convert.ToDouble(readdata["overdraftlimit"])).ToString();
Adjust to fit whatever data type is necessary for these two fields.
Considering that balanceDB is a string. Have you tried this:
balanceDB = readdata["balance"].ToString() + readdata["overdraftLimit"].ToString();
I assume you are trying to do this with a DataReader, right?
You will need to read in each column separately, and concat them together. The code below assumes you are working with strings. If they are integers, or some other type, you need to cast accordingly
balanceDB = readdata["balance"].ToString() + readdata["overdraftlimit"].ToString();
I assume that readdata is a DataTable/datareader and what you want is to add values of balance and overdraftLimit.
int balanceDB;
balanceDB = (Convert.ToInt32(readdata["balance"])+Convert.ToInt32(readdata["overdraftLimit"]));
Supposed the value of balance =1 and overdraftLimit=1 then balanceDB will be equals to 2
Or if you just need to concatenate the two strings:
string balanceDB;
balanceDB = readdata["balance"].ToString()+readdata["overdraftLimit"].ToString();
balanceDB will be equals to 11.
Regards

Categories

Resources