Retrieve last record of SQL Server table - c#

Here is the my problem: I have a SQL Server database called emp. It has an employee table (with userid int column). I need to retrieve the last record of the userid in employee table with increment userid value + 1. At the moment I did it on the my GUI. So how do I write a sql query for it?

To return the the record with the highest userid, you can do:
SELECT TOP 1 userid
FROM employee
ORDER BY userid DESC
or...
SELECT MAX(userid)
FROM employee
If your plan is to then increment the userid manually and insert a new record with that new ID, I'd recommend against doing that - what if 2 processes try to do it at the same time? Instead, use an IDENTITY column as userid and let the incrementing be handled for you automatically

You shouldn't be manually incrementing the userid column, use an IDENTITY column instead. That will automatically add 1 for you for every new row.
CREATE TABLE Employees (
UserId INT IDENTITY PRIMARY KEY NOT NULL,
UserName NVARCHAR(255) NOT NULL,
// etc add other columns here
)
If you really really have to select the highest userid it is a very simple query:
SELECT MAX(UserId) + 1
FROM Employees
[Edit]
Based on your comments, you should use the SELECT MAX(UserId) + 1 FROM Employees query. But be aware that this does not guarantee the number will be the ID. Normally you would not show an Id value until after the record has been saved to the database.

This will give you last inserted record, If you don't have Identity column.
EXECUTE ('DECLARE GETLAST CURSOR DYNAMIC FOR SELECT * FROM [User]')
OPEN GETLAST
FETCH LAST FROM GETLAST
CLOSE GETLAST
DEALLOCATE GETLAST
If you have set identity than you can use following.
SELECT top(1) ID from [YourTable] order by ID desc

To have the new userid before saving, create a NextId table.
Before inserting the user, get the new value from NextId:
UserId = SELECT Coalesce(NextId, 0) + 1 from NextId
Then update the NextID table:
UPDATE NEXTID SET NextId = IserID
And then use that value in your user creation code
You can get gaps, there are more complicated methods to avoid them; but I think this will do

Related

Create an id autoincrement with dapper

I'm working with Dapper and .Net 6.0... I have to do an insert from table1 to table2... in the insert the columns match each other... the only column is "toID" of table1... which does NOT match the column of table2 (that's why I put a 4 in it) but I have to make it auto-increment so that for each insert there is an incrementing sequence
var sql =
$"INSERT INTO table1 (toId,teId,dateShift,SectorOrigen) SELECT 4,teID,#dateModify,#LastSector FROM table2";
That is to say... that when I generate an insert the ID = 1, then another ID = 2 and so on continuously
Any advice??
You can create and use the sequence https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-ver16

C# MySQL transaction duplicate entry exception [duplicate]

I have a table with 3 columns - id (pk), pageId (fk), name. I have a php script which dumps about 5000 records into the table, with about half being duplicates, with same pageId and name. Combination of pageId and name should be unique. What is the best way to prevent duplicates being saved to the table as I loop through the script in php?
First step would be to set a unique key on the table:
ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name);
Then you have to decide what you want to do when there's a duplicate. Should you:
ignore it?
INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo");
Overwrite the previously entered record?
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "first")
ON DUPLICATE KEY UPDATE (somefield = 'first')
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "second")
ON DUPLICATE KEY UPDATE (somefield = 'second')
Update some counter?
INSERT INTO thetable (pageid, name)
VALUES (1, "foo"), (1, "foo")
ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1)
You can also ignore the error with mysql: INSERT IGNORE INTO TABLE ... it will ignore the key error, skip over that insert and move on to the next.
From a mysql point you can do
alter table YOURTABLE add unique index(pageId, name);
If your wording is correct and you want to do it from php you can do
$already_done = array();
foreach ($records as $record)
{
$unique_hash = md5($record['name'].$record['pageId']);
if (!in_array($unique_hash, $already_done))
{
$already_done[] = $unique_hash;
// sql insert here
}
}
either way those should do you just fine.
You can set the PageID and Name to a Unique index in the MySQL database. This way when you insert the rows, it will cause an error, which can be ignored by PHP, and you can just go to the next row.
This assumes you are inserting rows individually. AKA:
foreach($large_data as $fields)
{
mysql_query("INSERT INTO TABLE (`Something`) VALUES('".$fields['something']."');
}

Returning data which is not found in where clause and didn't update in sql

In a c# desktop application I am getting this list of data which I am reading by barcode into text file; here is the result;
R900, 27674T07, 27438T17, 27736T21, 26609T08,
R901, 27770T12, 27833T07, 26402T12, 27771T09, 26003T13,
R902, 26003T14, 26402T11, 26246T17,
R904, 28055T09, 25356T08, 25825T07, 25556T09,
and I am transforming it to update queries;
UPDATE TABLE SET NUMBER = R900 WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
UPDATE TABLE SET NUMBER = R901 WHERE id in ( 27770T12, 27833T07, **26402T12**, **27771T09**, 26003T13)
UPDATE TABLE SET NUMBER = R902 WHERE id in ( 26003T14, **26402T11**, 26246T17)
UPDATE TABLE SET NUMBER = R904 WHERE id in ( 28055T09, 25356T08, 25825T07, **25556T09**)
Finally I am executing this SQL query. But the problem is I don't know which id is not found in IN clause in database. I need to report back to user which id didn't found with its NUMBER
For example the bold id's are not found in database, and couldn't update. So expected result is:
NUMBER id
R901 26402T12
R901 27771T09
R902 26402T11
R903 25556T09
how can I return this?
You could do something like this
declare #mytable as TABLE
(
Id nvarchar(20)
)
UPDATE TABLE SET NUMBER = R900
OUTPUT INSERTED.Id into #mytable
WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
Select * from #mytable
#mytable will contain updated Ids only.
Hope this helps.
create a temp table to store the splitted value into it.
then
SELECT temp.number, temp.Id
FROM #temp temp
LEFT OUTER JOIN TABLE ON temp.id = TABLE.id
WHERE TABLE.id is null

Mysql normalization? Or another way?

After reading up on some normalization, it seems I am not quite grasping the concept.
What I am attempting to do is create a table that holds information for an item raffle.
So information for the item is ItemName, and Defindex.
After that, I need to have the "tickets" for the raffle, and to which user they went to. I want to limit the number of tickets sold.
So TicketA, TicketB, TicketC, TicketD.
Is there a query that I can use to insert a player name into TicketA if it's not full, or TicketB if A is full, so on until all tickets are sold?
Here's a sample to get you started: SQL Fiddle
Setup the basic tables to keep track of raffles and tickets.
CREATE TABLE Raffle
(
Id BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY
,Name VARCHAR(50) NOT NULL
,WinnerLimit INT NOT NULL
);
CREATE TABLE RaffleTicket
(
Id BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY
,RaffleId BIGINT NOT NULL
,UserId BIGINT NOT NULL
);
Setup a view to determine whether a raffle has any tickets left.
CREATE VIEW RaffleStatus
AS
SELECT Id AS RaffleId,
CASE WHEN EXISTS
(
SELECT 1
FROM RaffleTicket rt
WHERE rt.RaffleId = r.Id
GROUP BY rt.RaffleId
HAVING COUNT(rt.RaffleId) = r.WinnerLimit
)
THEN 1
ELSE 0
END AS SoldOut
FROM Raffle r;
Create a procedure to prevent overselling tickets. Note this probably isn't safe for multithreaded use.
DELIMITER //
CREATE PROCEDURE InsertRaffleTicket (IN userId BIGINT, IN raffleId BIGINT)
BEGIN
INSERT INTO RaffleTicket(UserId, RaffleId)
SELECT userId, raffleId
FROM RaffleStatus rs
WHERE rs.RaffleId = raffleId
AND rs.SoldOut = 0;
END//
DELIMITER ;
I want to limit the number of tickets sold.
That is business logic, not something that should reside in your database.
What if you want to query all raffles user X has attended? select * from raffles where ticketA = 'UserX' or ticketB = 'UserX' or ticketC = 'UserX'...
Just normalize it and check the ticket count from code.
One table of people, one of tickets, one of raffles.
Each ticket has the ID of the person and of the raffle.
As the previous answer, beyond that is business logic that shouldn't be in the DB. At most, you should "release" a batch of tickets for a raffle by creating them in the tickets table and then when a person wants to buy one you take the first ticket with the correct raffle ID and a null person ID.

Create an unique ID for multiple rows SQL

I have a number of user ID's. I am inserting these into a group table which will contain a column for the user's ID and the group ID. This will allow me to use the query "SELECT user_id FROM groups WHERE group_id = '3';" to retrieve user ID's of all the members of group 3.
My problem is that I currently have a list of all users IDs, which I got from a form, using the statements :
int i = 0;
String[] names = { Request.Form["usernames"]Split(' ') }; //retrieving names from form
List<int> user_ids = new List<int>();
foreach(string name in names){
int user_id = db.QueryValue("SELECT user_id FROM users WHERE username = name");
user_ids.Add(user_id); //now I have a list of all user_ids
}
I now wish to insert this data into the groups table, where all of the user_id values in the list will have the same group_ID. How can I do this?
//create a group from users
"INSERT INTO group (group_id, user_id) VALUES(?,?);
What you are talking about is a many-many relationship. You already have a users table:
**users**
userid
username
You need an additional table in the middle. The group table will just have something like:
**group***
groupid
groupName
You would then have a table in the middle. This table would look something like this:
**user_groups**
userid
groupid
You could still use your code to insert a user,
int i = 0;
String[] names = { Request.Form["usernames"]Split(' ') }; //retrieving names from form
List<int> user_ids = new List<int>();
foreach(string name in names){
int user_id = db.QueryValue("SELECT user_id FROM users WHERE username = name");
user_ids.Add(user_id); //now I have a list of all user_ids
}
After this, you would insert a group:
insert into group(groupName) values("Sample Group")
Then you could retrieve the group id and use that to insert into user_groups
select groupid from group where groupname="Sample Group"
insert into user_groups(userid,groupid) values(...
Also, the table structure should include primary keys and foreign keys (much like #sixlettervariables' answer)
In order to make this cleaner, you'll probably want to refactor your database setup slightly such that a third table relates users to groups:
users (user_id pk, ...)
groups (group_id pk, ...)
membership (user_id fk, group_id fk) unique(user_id, group_id)
When you needed to make a new group you simply insert into the groups table, obtain the group_id, and use that to populate the membership table for each of the users in that group.
You can use the select as the input to the insert
INSERT INTO group (group_id, user_id)
SELECT 1, user_id FROM users WHERE username in ("name1", name2")
You can join the names array back together with some commas.
You will need to iterate the user_ids list and do a separate insert statement for each user id.
You can insert all of the User ID's from one table into another using a sub-select and union statement as follows:
INSERT INTO group_table_name([user_id]) SELECT [user_id] FROM table_name
UNION ALL
By the way, you might want to change that table name since "group" is a keyword in SQL Server. Just a tip.
Insert Into GroupTable (GroupId, UserID) Select GroupID, USerID from UserTable group by GroupID, UserID)
This would work :)
Assuming you already know 3, you can do this without pulling the user ids into a local list and then inserting them individually (put in quotes specifically because the OP has their query in a similar string):
"INSERT dbo.group(group_id, user_id)
SELECT 3, user_id
FROM dbo.users
WHERE username = name;"
If you don't already know the group id, then please explain how you determined the group id should be 3.
EDIT based on further info.
CREATE TABLE dbo.Groups
(
GroupID INT IDENTITY(1,1) PRIMARY KEY,
GroupName NVARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE dbo.GroupUsers
(
GroupID INT NOT NULL FOREIGN KEY
REFERENCES dbo.Groups(GroupID),
UserID INT NOT NULL FOREIGN KEY
REFERENCES dbo.Users(UserID),
PRIMARY KEY(GroupID, UserID)
);
Now when you want to create a new group and add users to it:
DECLARE #GroupID INT;
INSERT dbo.Groups(GroupName) SELECT N'whatever (unique)';
SELECT #GroupID = SCOPE_IDENTITY();
Now you can loop through each user id:
INSERT dbo.GroupUsers(GroupID, UserID) SELECT #GroupID, <userid>;

Categories

Resources