How to insert multiple records on Transaction - sql-server

I have a question about SQL Server transactions
I want to insert datas into Table_A and Table_B.
Table_B has a Table_A's key.
Table_B's records size (has Table_A's key) is dynamic.
[Table_A]
id: ,
title:
[Table_B]
id: ,
tableA_id:,
title:
My code work only the case insert data is static size.
like this
var tableBtitles = ['abc','def','ghi'] //this size is dynamic
const transaction = new sql.Transaction()
transaction.begin(err => {
const request = new sql.Request(transaction)
request.query("insert into tableA (title) output Inseted.Id values('a')" , (err, result) => {
const request = new sql.Request(transaction)
request.input('tableA_id',mssql.NVarChar,
result['recordset'][0]['id']);
request.input('title1',mssql.NVarChar,
tableBtitles[0]);
request.input('title2',mssql.NVarChar,
tableBtitles[1]);
request.input('title3',mssql.NVarChar,
tableBtitles[2]);
request.query('insert into tableB (tableA_id,title) values(#tableA_id,#title1),(#tableA_id,#title2),(#tableA_id,#title2)), (err, result) => {
transaction.commit(err => {
})
})
})
Please tell me how to do it.

try this syntax
insert into [Table_A] ([data])
output inserted.id, inserted.data into [Table_B]
--check here
https://stackoverflow.com/a/3712735/8543453

Related

Linq EF6 adding multiple columns in a table from a list - Skips even rows

My application is MVC 5; I am trying to add multiple columns form a list into a table using:
var mylist = itemsToUpdate.Select(item => new
{
FirstName = item.FirstName,
LastName = item.LastName,
SNumber = item.SNumber
}).ToList();
foreach (var item in mylist)
{
var notification = new NotificationOld
{
FirstName = item.FirstName,
LastName = item.LastName,
SNumber = item.SNumber
};
db.NotificationOlds.Add(notification);
}
await db.SaveChangesAsync();
I get duplicates of row missing even number rows.
UPDATE:
The issue was in how I developed my SQL view by using:
ROW_NUMBER() OVER(ORDER BY dbo.LearnersOld.ID) AS SNumber

Dapper QueryAsync with two params

I'm wondering if there is a way to do something like this:
string sql = "SELECT * FROM TABLE WHERE ID = #ID AND VALUE = #VALUE";
var listTest = await _dbConnection.QueryAsync<Example>(sql, ID, VALUE);
I want to query a table with a Composite PK.
var listTest = await _dbConnection.QueryAsync<Example>(sql, new { ID, VALUE });

EF optimize multiple order by select top 1

I have the following Entity Framework query:
var queryResponse = await db.DataPoints.GroupBy(x => x.Device).Select(x => new
{
lon = x.Key.DataPoints.OrderByDescending(y => y.DateTime).Select(y => y.Longitude).FirstOrDefault(),
lat = x.Key.DataPoints.OrderByDescending(y => y.DateTime).Select(y => y.Longitude).FirstOrDefault(),
date = x.Key.DataPoints.OrderByDescending(y => y.DateTime).Select(y => y.DateTime).FirstOrDefault(),
label = x.Key.Name,
})
.OrderByDescending(x => x.label)
.ToListAsync();
Now you can see in my select, I have to get lon,'lat', and 'date'. However the way im doing it, I have to orderby and select the first one 3 times. The 'DataPoints' is a very large table.
in C# i would normally do the orderBy once and just select the entire object, and then later on break it up into the 3 properties. However in this case I want SQL to return the exact fields.
is there a more efective way to write this query?
Try this:
var queryResponse =
(from g in db.DataPoints.GroupBy(x => x.Device)
let latestDataPoint = g.Key.DataPoints.OrderByDescending(p => p.DateTime)
.FirstOrDefault()
select new
{
lon = latestDataPoint.Longitude,
lat = latestDataPoint.Latitude,
date = latestDataPoint.DateTime,
label = g.Key.Name
})
.OrderByDescending(x => x.label)
.ToList();

Check record in SqLite (ionic)

Does anybody know, that how can I check an inserted record? I would like to create an intro page. When the user visits once, I wanna store it and check it.
$rootScope.insert = function(visited) {
var query = "INSERT INTO shoplist (visited) VALUES (?)";
$cordovaSQLite.execute(db, query, [visited]).then(function(res) {
console.log("INSERT ID -> " + res.insertId);
}, function (err) {
console.error(err);
});
}
$rootScope.insert(1);
Basically I would like to check that visited record is 0 or 1.
What should I do?
You can just write the query
Select from shoplist Where id = ?
Where id is the one your insert returned.

Bulk insert data in mssql table using node mssql

I am using node-mssql
My query file is as below
BEGIN TRANSACTION
DECLARE #status NVARCHAR(30);
SET #status = 'create';
DECLARE #i UNIQUEIDENTIFIER;
SET #i = NEWID();
DECLARE #t DATETIME2;
SET #t = SYSUTCDATETIME();
IF NOT EXISTS(
SELECT * FROM user WHERE email = #email AND company_id= #company_id
) BEGIN
SET #i = NEWID();
INSERT INTO user (comapny_id, id, email, password) VALUES ( #company_id, #i, #email, #password);
INSERT INTO user_transaction( id, date, type) VALUES ( #i, #t, #status);
SELECT #i as 'id', #email as 'email';
END ELSE BEGIN
SELECT NULL as 'id', #email as 'email';
END
COMMIT TRANSACTION
And my createuserquery in query.js file is
datastore.getQueryFromSqlFile('create_user', (err: any, query: string) => {
if (err) {
done(err);
} else {
var request = new sql.Request(connectionOrTransaction);
request.input('email', sql.NVarChar(200), email);
request.input('password', sql.NVarChar(200), some_password);
request.input('company_id', sql.UniqueIdentifier, company_id);
request.query(query, function (err, data) {});
Now I need to modify these to insert bulk of user data imported from CSV file (>20000 entries)
I was thinking of doing something like
async.mapSeries(Object.keys(users), function (item, callback) {
query.createuser(email, company_id, function (err, data) {
callback(err, err ? 'Error message: ' + data : data);
});
}, function (err, results) {
})
But this is not efficient as I get connection timeout. Increasing connectionTimeout or requestTimeout in config file doesn't help much.
How could I make my query faster for bulk insert around 20000-40000 entries in per attempt?
For me it looks like a job for a prepared statement.
var ps = new sql.PreparedStatement();
ps.input('email', sql.VarChar);
ps.input('password', sql.VarChar);
ps.input('company_id', sql.Int);
ps.prepare(" ... your sql ... ", function(err) {
// ... error checks
// users must be an array of users
async.mapSeries(users, function(user, next) {
ps.execute({email: user.email, password: user.password, company_id: user.company_id}, next);
}, function(err) {
// ... error checks
ps.unprepare(function(err) {
// ... error checks
// done !
});
});
});
Every execute is called as a single request, so you should not be timeouted by requestTimeout. connectionTimeout is something that only affect connecting phase. Once you're connected to db, only requestTimeout matters.

Resources