Making a substring plus data from sql database column - c#

I am trying to create, lets say a user ID. I have a sql server database and i have a user webpage developed in asp.net. On my user page, a user fill out the information in the text boxes(First Name, Last Name, Middle Initial and so on) and when a user clicks a submit button, the entered information is added to a database. I have an auto increment column in the database, so when the information is added to the database the row has a auto increment number, for example 1. Each time the new row is added the auto increment number rises on one.
I want to create an unique UserID. It should contain the first 4 letters of a Last Name, which user fills out on a user web page and the auto increment number from the database. I have a code to retrieve the first 4 letters of the last name ( string FirstFour = txtNewUserLN.Text.Substring(0, 4);) but i need to add auto increment number from the database to that string.
Could anyone help me with it?

Create an sql user defined function in sql database
for create an function
use
CREATE FUNCTION ucernamehandle(#Lastname)
RETURNS nchar(50)
AS
BEGIN
DECLARE #idfromauo int;
DECLARE #newusernem nchar(50);
SET #idfromauo =IDENT_CURRENT('yourtablename');
return #Lastname+#idfromauo;
END
and then use it in inset statement like
INSERT INTO yourtablename (LastName) VALUES (ucernamehandle(#Lastname))
then exactly you will get witch you want
welcome for your thank's
best of luck

My guess is you are going to have to do an insert and then an update. Something to watch out for - if you use anything that checks for the last or just inserted identity value, make sure you put it in a transaction. If you don't you could have other processes adding a record before you update.
So try something like this:
insert into UserList(LastName, FirstName, ...) values (#LastName, #FirstName)
declare #UserID varchar(500)
set #UserID = left(#LastName, 4) + convert(varchar(10), SCOPE_IDENTITY())
update UserList set UserID = #UserID where RowID = Scope_identity()

Related

sql-server primary key (ID) does not increment correctly

I am working on a project with C# and SQL Server 2016.
In SQL Server Management Studio I add a primary key to an existing table, by right clicking the table and choosing design table, it worked fine.
But as soon as I add some new users and deleted some users, it started behaving strange, I mean after id=4 next user should have id=5 but instead it was given id=7.
Screenshot of SSMS
Actually you have deleted the users with id 5 and 6. The counter for the auto increment is not reset or reversed automatically. Its the normal and standard behavior.
This may sound unbelievable, but if you want an incrementing record number, SQL Server has no support for you. A transaction that is rolled back or a server restart can leave holes in the numbers.
If you delete a row, you'll have to implement that manually. Say that records 1, 2 and 3 exist. You delete record 2. What number should the new order get? If you say 2, remember that means order 2 is created after order 3, which would confuse a lot of people.
Probably records with Id 5 and 6 ar been deleted
IDENITY T-SQL
Specifically the 'Reuse of values'
'For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated. '
Hope this helps to explain
It might not just be that the records have been deleted. Every time you try to INSERT data into that table the seed will be incremented. Take, as a very simple example:
CREATE TABLE #Sample (ID int IDENTITY(1,1), String char(1));
GO
INSERT INTO #Sample (String) VALUES ('A'); --This'll get ID 1
GO
INSERT INTO #Sample (String) VALUES ('AB'); --This'll get ID 2, but fail insertion (due to truncation)
GO
INSERT INTO #Sample (String) VALUES ('C'); --This'll be ID 3.
GO
--Let's Check.
SELECT *
FROM #Sample;
GO
--The SAme is tue for Transactions.
BEGIN TRANSACTION;
INSERT INTO #Sample (String) VALUES ('Q'); --This'll get ID 4
ROLLBACK;
INSERT INTO #Sample (String) VALUES ('S'); --This'll get ID 5
SELECT *
FROM #Sample;
GO
--DELETE
--Let's delete EVERYTHING
DELETE
FROM #Sample;
INSERT INTO #Sample (String) VALUES ('A'); --This'll get ID 6, Not 1
SELECT *
FROM #Sample;
GO
--Finally, howerver, truncate:
TRUNCATE TABLE #Sample;
--Truncate RESETS the seed.
INSERT INTO #Sample (String) VALUES ('A'); --This'll be 1;
SELECT *
FROM #Sample;
GO
--Clean up
DROP TABLE #Sample;
Hope that helps.
Assuming that you have used the identity feature in SQL server. When you try to insert a new record into a table having an identity column, the identity value will be increased even if the insert failed due.
Suppose I have a table where the identity column SeqNo have the current value as 9 and incremented by 1.
I'm inserting a new record but it failed due to some data issues.
So I fixed the issues are tried re-inserting the same.
Assuming no other inserts happened during this time, the SeqNo for the new record should be 10, but it will be 11.
because SQL Server won't roll back the Identity Seed if the insert fails. So you will have to manually re-seed the column
Same in the case of delete and insert. I have the Maximum SeqNo as 5.I deleted the SeqNo 5 and inserted a new record, but for my new record, the SeqNo will be 6 (or the next identity value)
So, if you want to specify some values to the identity column, try inserting with SET IDENTITY INSERT ON. like this
SET IDENTITY INSERT YourTable ON
INSERT INTO YourTable(SeqNo,Name)
VALUES(5,'ABC')
SET IDENTITY INSERT YourTable OFF
When we delete of cancel(by pressing ESC button while filling values in table), it takes it as increment, you can truncate your table(
NOTE: Truncate will delete all values from your table
)

Can I reserve a place for id in SQL Server on form load

I have retrieved the last ID incremented by 1 into a textbox on form load, but is there a way to reserve a place in the table for this ID (that is retrieved), until form is saved?? Because there are multi users using this form and i need to get an ID once form is loaded, although form might take more time to be saved.
Am using c# for my application,i don't know if i have to implement this on my code application or in database itself.
You can change the current value of identity column by executing the following code
DBCC CHECKIDENT ([TableName], RESEED, 50)
But keep in mind that for inserting your record you must first set IDENTITY_INSERT on and then set it off like
SET IDENTITY_INSERT [dbo].[TableName] ON
INSERT INTO [dbo].[TableName] ([Id], [Title]) VALUES ( 50 , '123' )
SET IDENTITY_INSERT [dbo].[TableName] OFF
You can save the row with minimal data and then update record when form is saved. You need to add a flag to mark invalid condition on data of this row. Maybe you need to clean up records marked as invalid periodically.
Another possible solution is create an aux table to store generated IDs but maybe, you must add additional information to know which is the origin, i.e., a reference to form.

Get last generated ID and add it to another table ASP.NET

How can I get get generated ID from primary key and then add it to another table in ASP.NET via SCOPE_IDENTITY?
For example:
Last generated ID on column NRRENDOR is number 26, I have deleted the rows. Now when I add datas to the database the nexy generated ID on NRRENDOR will be number 27. That number I want it to add to column NRD.
In your INSERT code, assuming it's in a stored procedure, using SCOPE_IDENTITY will get you the last identity that was inserted, which you can either reuse in the stored procedure or return to your app to use in another statement.
Some dummy SQL to demonstrate:
INSERT INTO NRRENDOR(SomeColumn) VALUES(1)
DECLARE #LastID int
// set #LastID to the last id inserted
SELECT #LastID = SCOPE_IDENTITY()
// to use in same procedure
INSERT INTO NRD (SomeColumn) VALUES(#LastID)
// to return it to code - or you could use an output parameter
SELECT #LastID
What has this got to do with ASP.NET? SQL would suffice.
INSERT INTO [Table2]( NRD)
SELECT MAX(NRRENDOR)
FROM Table1
' WITH (ROWLOCK, XLOCK, HOLDLOCK)
The correct way to do it will be to use #SCOPE_IDENTITY after you perform insertion as Tanner suggested. It will be worth noting that there is another way to get the current identity, ie, IDENT_CURRENT. You can use it like this
SELECT IDENT_CURRENT('Table1') + 1 as Current_Identity
Please note this too
Be cautious about using IDENT_CURRENT to predict the next generated
identity value. The actual generated value may be different from
IDENT_CURRENT plus IDENT_INCR because of insertions performed by other
sessions.
This comment from marc_s sums it all. How to get the next identity value from SQL Server

Check for new/existing values and update in sql

I have a SQL table with Project Column value as 'Project1,Project2,Project3'
I need to update this row if they select a different value like 'Project4' from the telerik dropdown list as 'Project1,Project2,Project3,Project4'
I get the value from the dropdown same as 'Project1,Project2,Project3',so I will send this as a paramter to SQL.
Suppose if they select 'Project5,Project1'...Project1 should not be added as its already there.
Can some one suggest how do I check for new and existing values and update accordingly.
My simple update is not working for this scenario.Kind of struck.
Thanks
You can create a stored procedure and use merge to insert or update as necessary like the example below
DECLARE #nameField VarChar(50) = 'some data'
MERGE dbo.MyTable t
USING (SELECT #nameField [field]) s
ON t.myData = s.field
WHEN MATCHED THEN
UPDATE
SET t.myData = #nameField
WHEN NOT MATCHED THEN
INSERT (myData)
VALUES (#nameField);
If you want to limit redundant updates, e.g. if updating Project Column with the exact same data and block such updates, then you'll need to create an update trigger to check and block the update.

How to save a new record when the id key is auto incremented

I have created a database in sql server 2008 and a table with auto increment id field
Also I develop a project in c#.net 2008
The problem occurs on click "save data" after of "add new" from BindingNavigator
for example I click "add new", fill all fields except id text (blanked id) and then click 'save data' then occurs the errors
The runtime exception is "notNullAllowedException: the column 'id' not allowed null.
But it is not required from the user to fill this field but has to returned from database after the save
I also set the properties of the id: (both c# project and sql server)
AutoIncrement = True
AutoIncrementStep = -1 (also I tested 1)
AutoIncrementSeed = -1 (also I tested 1)
No results.
How I could handled that?
Thanks
Don't include the identity column in your Insert statement.
If your statement is
INSERT INTO MyTable (ID, SomeField, SomeOtherField) VALUES (null, 'SomeValue', 'AnotherValue')
simply change it to
INSERT INTO MyTable ( SomeField, SomeOtherField) VALUES ( 'SomeValue', 'AnotherValue')
It sounds like you have two problems.
First, you're always inserting - what logic do you use to decide whether 'save' should be an insert or an update? I think this is the case becuase of the errors you're getting: "Cannot insert explicit..."
Second, you need to get the ID that SQL assinged on your insert so you can write it to your ID field for the next save=update. There are a couple of ways to do this, the way I prefer is to use a stored procedure to do the insert and pass an OUTPUT parameter that gets SCOPE_IDENTITY(). Something like this:
CREATE PROC xyz
(
#data...
#NEWID INT OUTPUT
)
AS
... do your INSERT ...
SET #NewID = SCOPE_IDENTITY()
)
double-check my syntax - not sure what version of SQL you're using

Categories