Create an id autoincrement with dapper - c#

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

Related

Preventing duplication from SQL Query, ASP.net

I have the below SQL query using the Query Builder in Visual Studio. As you can see the same user is duplicated 3 times, this is due to the user having 3 different skills. How can I merge the 3 skills together in the SQL query or in a ListView control so that it only displays one result instead of 3 and that the user has their 3 skills listed?
SELECT users.role_id, users.username, users.first_name, users.last_name, users.description, roles.role_id, roles.role, skills.skill_id, skills.user_id, skills.skill
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN skills ON users.user_id = skills.user_id
WHERE (users.role_id = 3)
Use For XML Path(''), Type. It is a bit of a hack, because you're really creating an XML string without a root and fashioning odd elements, but it works well. Be sure to include the Type bit, otherwise the XML trick will attempt to convert special characters, like < and & into their XML escape sequences (here is an example).
Here is a simplified version of your problem in a SQL Fiddle. Below is the relevant Select snippet.
SELECT users.user_id, users.first_name,
STUFF(
(SELECT ', ' + skill
FROM skills
WHERE users.user_id = skills.user_id
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
, 1, 2, '') AS skill_list
FROM users
Try using Stuff and For Xml
Here's the Fiddle:
http://sqlfiddle.com/#!6/fcf71/5
See if it helps, it's just a sample so you will have to change the column names.
You can use PIVOT on the Skill then group those skills into one column.
To make it simple, I test it with some sample data like the following:
CREATE SCHEMA _Test
CREATE TABLE _Test.SkillSet(SkillId INT IDENTITY(1,1) PRIMARY KEY, SkillName NVARCHAR(64))
INSERT INTO _Test.SkillSet(SkillName) VALUES('C/C++')
INSERT INTO _Test.SkillSet(SkillName) VALUES('C#')
INSERT INTO _Test.SkillSet(SkillName) VALUES('Java')
CREATE TABLE _Test.Employees(EmpId INT IDENTITY(1,1) PRIMARY KEY, FullName NVARCHAR(256))
INSERT INTO _Test.Employees(FullName) VALUES('Philip Hatt')
INSERT INTO _Test.Employees(FullName) VALUES('John Rosh')
CREATE TABLE _Test.Employee_Skill(EmpId INT FOREIGN KEY REFERENCES _Test.Employees(EmpId), SkillId INT FOREIGN KEY REFERENCES _Test.SkillSet(SkillId))
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 1)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 2)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 3)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(2, 2)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(2, 3)
WITH tEmpSkill
AS
(SELECT A.EmpId, A.FullName, C.SkillName
FROM _Test.SkillSet C RIGHT JOIN
(
_Test.Employees A LEFT JOIN _Test.Employee_Skill B
ON A.EmpId = B.EmpId
)
ON B.SkillId = C.SkillId
)
SELECT * FROM tEmpSkill
PIVOT(COUNT(SkillName) FOR SkillName IN([C/C++], [C#], [Java])) AS Competency
The query above gives me an intermediate result
PIVOT RESULT
Now you can easily make a string containing all the skills needed for each employee. You can also search for some articles to use the PIVOT with unknown number of columns (skill sets), which may better serve your need.
Hope this can help.

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

how to update the selected rows in same query?

I have 1 table table1, and a select query
select col1 from table1 where id <= 10;
I want to update the same records
update table1 set col2 = 'some value' where id < 10;
I want to do both the operations in 1 query and get the selected result also so that i can use it.
How can I do that?
You can not update and select row using one single query, since both are different operation.
So you need to write 2 different queries.
If you don't need to update table and want temporary output, then #Yosi had provided you with perfect solution.
You don't have to update it, you an use CASE statement:
SELECT col2 = CASE WHEN id<=10 THEN 'some value' ELSE col1 END
FROM table1
Try this sql query using OUTPUT to get the updated vlaue
UPDATE persons
SET LastName = 'test'
OUTPUT Inserted.LastName
where id<10;
If you need the old value after updation:
UPDATE persons
SET LastName = 'test'
OUTPUT DELETED.LastName
where id<10;
DEMO

A Query Copy from 1 table into another + Values

I am trying to make this query work but i keep getting error.
insert into Table1 (CL1,CL2) Values ('TEST',CL2)
SELECT CL2 from Table2 where ID = 2
I am trying to take data from table 2 and put it in table 2 with the name TEST
Table1
is Empty
Table2
ID=2,SUP,SUP,SUP
if any one can help it would be great
insert into Table1 (CL1,CL2) SELECT 'TEST', CL2 from Table2 where ID = 2
Is this what you want:
INSERT INTO Table1 (CL1,CL2) VALUES ('TEST',(SELECT CL2 FROM Table2 WHERE ID=2))

Retrieve last record of SQL Server table

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

Categories

Resources