Identify transaction with default value table SQLServer - sql-server-2008

I have a table where I do only INSERT operations.
I'd like to uniquely identify these transactio operations through a unique default value (I could do some sequentially INSERT in a transaction that i want to identify with a same id).
Example:
BEGIN
INSERT INTO Table_Example (Id, Value)
VALUES (1,'TEST'), (2,'TEST 2'), (3,'TEST 3)
INSERT INTO Table_Example (Id, Value)
VALUES (4,'TEST 4'), (5,'TEST 5'), (6,'TEST 6)
END
Result in Table_Example (Session_Id has been set as i'd like to do)
Id | Value | Session_Id
1 TEST sakmfnsakjnfms-jkfhsajfs-1
...
6 TEST 6 sakmfnsakjnfms-jkfhsajfs-1
this can be accomplished through such a function or is there any best practices?

Related

Is there any way to order result by column value?

I have MySQL table with many columns.
id|Date |col1|col2|col3|col4|col5|... |col500|
-----------------------------------------------------------------
1|01.10.2019| 152| 99| 0|1598| 48| filled with zeros| 1|
-----------------------------------------------------------------
2|02.10.2019| 12| 344| 19|2544| 3| filled with zeros| 152|
-----------------------------------------------------------------
....
Is it possible to order column
SELECT * FROM table WHERE Date = '02.10.2019' ORDER BY COLUMNS
and get result like this
id|Date |col4|col2|col500|col3|col1|col5|... |
-----------------------------------------------------------------
2|02.10.2019 |2544| 344| 152| 19| 12| 3|filled with zeros
If you want to order by columns value, as Madhur Bhaiya and P.Salmon said, may be your table is not properly designed, and you are probably speaking of rows, and not of columns.
Instead of a table with columns ID/ Date/ col1/ col2/ ... / col500, perhaps you need a table like this
CREATE TABLE tbl(
pk integer not null primary key default autoincrement,
id integer not null,
dt date not null,
xxx_id integer,
value integer);
where XXX_ID represent the column position in your old table (may be an identifier of single record, I don't know what you are using this table for).
Now you have to insert the values:
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 152);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 99);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 0);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 1592);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 48);
....
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 12);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 344);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 19);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 2544);
...
And the answer to your question becomes very easy, something like
select * from tbl
where id = 1 AND date = '2019-10-01'
order by value
Last point: you can decide to insert records with ZERO value, or skip them, or insert them with NULL value. It depends on what is the goal of the table.

Add deleted record to auto increment table

I have a table having id set to auto increment.
I have records 1 to 10 and I have deleted records 3 and 7.
So is their any way I can add records 3 and 7 again?
Yes, you have to "force" the id.
INSERT INTO table (id, field1) VALUES (3, "value"); // id = 3
But if you let the id "null" or not set, it will be incremented :
INSERT INTO table (field1) VALUES ("value"); // id = 8
In Mysql You can override the auto-increment id simply assingning the value you need .. this is perfectly legal ..
so you can insert your row with id 3 and 7 using
insert into your_table (id, col1, col2 ..) values (3, 'value_for_col1', 'value_for_col2'...)
the autoincrement only works if no value is specified for the field, in other words you can insert the specifying the value of the field with autoincrement, example: insert in db.banks (id, description,status, created_at,updated_at) values ('3', 'Central Bank', '1', '2017-04-14 10:30:22', null);

MySQL: How do you update a field on duplicate key for a value other than 1?

I've seen the question regarding how to increment a column value when a duplicate insert is attempted:
insert into table (col) values (val) on duplicate update countcol=countcol+1;
But how do you increment the countcol by a variable value?
For example:
insert into table (col, count) values (val1, val2) on duplicate update count=count+val2?
Suppose I'm tracking the number of books read by students and my table contains:
Mark | 5
Mark reports reading 2 more books, so I want:
Mark | 7 (add 2 to existing total)
But I want to handle the case where Jerry (new to the program) reads 2 books
insert--> Jerry | 2
Maybe something like;
insert into readers (student, count)values ('Mark',3 as read)
on duplicate key update count=count+read;
Are there actual names/references I can access for the values submitted in mySQL? Can this be done in a single statement? Or do I need to first test to see if the record exists and then insert/update depending on the result?
Use values():
insert into table (col, count)
values (val1, val2)
on duplicate update count = count + values(count);
values() refers to the value being passed into the insert.

mysql update multiple id/value pairs with one statement

If I have a mysql table with the 2 columns:
ID Date
1 2012-03-05
2 2012-02-21
3 2013-06-12
4 2011-01-15
5 2013-02-23
and I have an array of random updates such as
$arr = array('2'=>'2013-03-23','4'=>'2013-03-19','5'=>'2011-08-09');
(where the index is the ID and the value is the date)
is there a way to update the table with one statement?
the reason I am doing this, is because I need to make hundreds+ of changes and single updates would be alot of statements.
If ID is unique or a primary key, you can do
INSERT INTO `Table` (ID, `Date`)
VALUES ('2', '2013-03-23'), ('4', '2013-03-19'), ('5', '2011-08-09')
ON DUPLICATE KEY UPDATE `Date` = VALUES(`Date`)
Note that this might affect the auto increment value and it might insert new records into the table.

table with records that can be arranged

How can I make a table that has rows with order to one another and can be rearranged:
Example:
Rows:idappearance name
Records
(1,"john"),(2,"mike")
Now, I want to insert "Avi" between them:
not having to worry about rearranging them
(1,"john"),(2,"Avi"),(3,"mike")
This table can have a foreign key in
another table (like departments..).
idappearance is the order of appearance I want
to set, doesn't need to be PK.
It needs to handle about 50K of names so O(n) isn't best solution.
Simple solution would be having reasonable numerical gaps between records. In other words;
(10000,"John"),(20000,"mike")
(10000,"John"),(15000,"Avi"),(20000,"mike")
(10000,"John"),(12500,"tom"),(15000,"avi"),(20000,"mike")
etc..
Gap between records should be determined based on your data domain
You could have a trigger on inserts. I don't use MySQL, but here's the code for sql-server...
Basically, on an insert, the trigger increments the appearanceId of all rows with appearanceId which are equal to or greater than the new appearance id.
CREATE Table OrderedTable
(
id int IDENTITY,
name varchar(50),
appearanceOrder int
)
GO
CREATE TRIGGER dbo.MyTrigger
ON dbo.OrderedTable
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE OrderedTable SET
AppearanceOrder = AppearanceOrder + 1
WHERE AppearanceOrder >= (
SELECT TOP 1 AppearanceOrder
FROM inserted )
AND id NOT IN (
SELECT id
FROM inserted )
END
GO
INSERT INTO OrderedTable VALUES ('Alice', 1)
INSERT INTO OrderedTable VALUES ('Bob', 1)
INSERT INTO OrderedTable VALUES ('Charlie', 1)
INSERT INTO OrderedTable VALUES ('David', 1)
This returns David, Charlie, Bob, Alice as expected.
SELECT *
FROM OrderedTable
ORDER BY AppearanceOrder
Note that I haven't fully tested this implementation. One issue is that it will leave holes in the AppearanceOrder if items are deleted, or the inserts deliberately insert outside the current range. If these matter, they are left as an exercise to the reader ;-)
If appearance order were a double-precision floating point number, you could insert any name between any two adjacent names with a single insert. If you start with a table like this:
create table test (
person_id integer primary key,
person_name varchar(10) not null,
appearance_order double precision not null unique
);
insert into test values (100, 'John', 11);
insert into test values (23, 'Mike', 12);
Insert Avi between them by simply
insert into test values (3, 'Avi', 11.5);
Sort by the column 'appearance_order'.
select * from test order by appearance_order
100 John 11
3 Avi 11.5
23 Mike 12
Insert Eva between John and Avi by
insert into test values (31, 'Eva', 11.25);
select * from test order by appearance_order
100 John 11
31 Eva 11.25
3 Avi 11.5
23 Mike 12
You do need to separate identification from sort order. That means using one column for the id number (and as the target for foreign key references) and another for the appearance order. But, depending on your application, you might not need a unique constraint on appearance_order.