I have an sql db with two columns A and B where A is an autoincrement. Is there any way to autofill a column C whenever an entry is inserted using Hibernate. The column C will be the concatenation of values in B and A i.e. B_A?
You could use a BEFORE INSERT TRIGGER (https://www.techonthenet.com/mysql/triggers/before_insert.php) which can change values for your insert.
CREATE TRIGGER addRow BEFORE INSERT ON table
FOR EACH ROW
BEGIN
SET new.C = concat(new.a, '_', new.b);
END
Edit:
You can fetch the auto increment value using:
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tbl');
SET NEW.field=next_id;
Use below query :
SELECT CONCAT(char_col,'_',CAST(int_col AS CHAR));
Related
Can you insert an autoincrement value into several columns at once?
Example table `zoo`:
id (int autoincrement primary_key);
parent (int);
data (varchar,10).
INSERT INTO zoo (id, parent, data) VALUES (NULL, id, "tiger");
Or do I have to do a second query?
UPDATE TABLE zoo SET parent=id WHERE parent IS NULL;
You might be able to do this via a before insert trigger:
DELIMITER //
CREATE TRIGGER same_id_trigger
BEFORE INSERT
ON zoo FOR EACH ROW
BEGIN
DECLARE id int DEFAULT 0;
SELECT auto_increment INTO id
FROM information_schema.tables
WHERE table_name = 'zoo' AND table_schema = database();
SET NEW.parent = id;
END; //
DELIMITER ;
Assuming the above trigger works, then it is working by directly querying information schema to find the current auto increment value for the zoo table. Then, the trigger effectively intercepts the insert, and swaps in that auto increment value for the parent column.
How to assign unique auto incrementing values to a certain column? Kind of like AUTO_INCREMENT does but it should be NULL at the time of insertion and assigned at some later point.
I have a table that gets regular data inserts and a few workers that process that data and set processed_at datetime field when they're done. Now I want incrementally select new processed rows since the last call. If I naively use where processed_at > #last_update_time I'm afraid there might be a situation where some records are processed at the same second and I miss some rows.
update: Can I just do
begin;
select #max := max(foo) from table1;
update table1 set foo = #max + 1 where id = 'bar' limit 1;
commit;
if foo column is indexed?
You can use a trigger to implement that.
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
CREATE TRIGGER pk AFTER UPDATE ON your_table_name
BEGIN
UPDATE my_increment
SET value = value + 1
WHERE table_name = 'your_table_name';
UPDATE your_table_name
SET ID2 = (
SELECT value
FROM my_increment
WHERE table_name = 'your_table_name')
WHERE ROWID = new.ROWID;
END;
But bear in mind that this trigger will work on every execution of the Update query.
You can also do it manually:
Create the table to store increment value:
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
Then when you want to update the table, get the last value from this table and insert value+1 to your column needed to be incremented.
I want to get rows of a table such that no column value is null. No hardcoding of column values. I have hundreds of column names so.
Output should be only row 2 since all that row has the values for all the columns. I do not want to specify all the column names for is not null. It should take it programmatically. Even if i add a new column it should work without changing the query. That is my vision.
I found something, but that means using CURSOR
DECLARE #ColumnName VARCHAR(200)
DECLARE #ColumnCount INT
DECLARE #sql VARCHAR(400)
CREATE TABLE #tempTable (Id INT)
DECLARE GetNonNullRows CURSOR
FOR
SELECT c.NAME, (SELECT COUNT(*) FROM sys.columns col WHERE col.object_id = c.OBJECT_ID) FROM sys.tables AS t
JOIN sys.columns AS c ON t.object_id = c.object_id
WHERE t.name = 'SomeTable' AND t.type = 'U'
OPEN GetNonNullRows
FETCH NEXT FROM GetNonNullRows INTO #ColumnName, #ColumnCount
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = 'SELECT st.UniqueId FROM SomeTable AS st WHERE ' + CONVERT(varchar, #ColumnName) + ' IS NOT NULL'
INSERT INTO #tempTable
EXEC (#sql)
FETCH NEXT FROM GetNonNullRows INTO #ColumnName, #ColumnCount
END
CLOSE GetNonNullRows
DEALLOCATE GetNonNullRows
SELECT * FROM SomeTable AS st1
WHERE st1.UniqueId IN (SELECT Id FROM #tempTable AS tt
GROUP BY Id
HAVING COUNT(Id) = #ColumnCount)
DROP TABLE #tempTable
Let me to explain this a little.
First i create cursor which iterate through all the columns of one table. For each column, I've create sql script to search in table for not null values for selected column. For those rows that satisfies criteria, I take its unique ID and put in temp table, and this job I am using for all columns.
At the end only ID's which count is like columns count are your result set, because only rows that have identical number of appearances like number of columns in table may be rows with all non null values in all columns.
Try this ::
SELECT * FROM mytable WHERE column IS NOT NULL
try this
SELECT *
FROM your_table_name
where coalesce(column_1, column_2, column_3, ...., column_n) is not null
SQL alone cannot express such a concept.
You have to dinamically build the SQL query according to the table definition using some procedural language.
In Oracle you can use the dictionay view USER_TAB_COLUMNS to build the column list.
try using IS NOT NULL
SELECT * FROM table WHERE field_name IS NOT NULL
For more information, check out the mysql manual on working with null values.
I have a working INSERT INTO SELECT query which inserts records into a new table based on the results of the select. Simple.
INSERT INTO my_table (a, b, c)
SELECT a, b, c FROM my_table
WHERE x=y;
How do I get the newly created primary key IDs from the INSERT part of this query so that I can use them to update another table? (The primary key is the only unique reference)
I have read that INSERT INTO SELECT only supports inserting into one table per query, so that's out of the question. How can this be accomplished (using MyISAM engine)?
YOu can select your data in a temp Table, then run cursor on that while inserting rows u ll have PK
DECLARE #tempTable TABLE(
a VARCHAR(MAX),
b VARCHAR(MAX),
c VARCHAR(MAX)
)
INSERT INTO #tempTable(a,b,c)
SELECT a,b,c FROM my_table WHERE x=y
DECALRE #a DATATYPE;
Declare #b DATATYPE;
Declare #c DATATYPE;
DECLARE cursor CURSOR FOR
SELECT * FROM #tempTable
OPEN cursor
FETCH NEXT FROM PropertyCursor INTO #a, #b,#c
WHILE (##FETCH_STATUS = 0)
BEGIN
INSERT INTO my_table(a,b,c)
VALUES(#a,#b,#c)
DECALRE #PrimaryKey INT = SCOPE_IDENTITY();//THis line will give u the PK so u can work with it and then below move to next row
FETCH NEXT FROM cursor INTO #a, #b,#c
END
CLOSE cursor
DEALLOCATE cursor
I'm trying to implement a custom sort field for a list of records. When I create a new record, by default I would like this field to match the ID number of that record. Is there any way to achieve this without having to perform two queries?
Any advice appreciated.
Thanks
You can get the next auto-increment id by using
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM `INFORMATION_SCHEMA.TABLES` WHERE table_name = 'tablename'
This will give you the next auto_increment value.
Then make a before insert trigger:
DELIMITER $$
CREATE TRIGGER bi_table1_each BEFORE INSERT ON table1 FOR EACH ROW
BEGIN
DECLARE next_id integer;
SELECT `auto-increment` FROM `INFORMATION_SCHEMA.TABLES` INTO Next_id
WHERE TABLE_NAME = 'table1' LIMIT 1;
SET new.sortcolumn = next_id;
END $$
DELIMITER ;
Links
http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
http://dev.mysql.com/doc/refman/5.0/en/tables-table.html
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
I think you can leave this field equal to NULL by default and then in your query do this:
ORDER BY ifnull(sort_field, id)
Set it to null or something like that by default and make your query sort by id if the sort field is null. PseudoSQL:
SELECT blah, IFNULL(t.sort, t.id) AS sortval
FROM t
ORDER BY sortval
You can use MAX(ID) expression to be sure that your next INSERT will be the greater id + 1 :
INSERT INTO table_name (..., sort_field) VALUES (..., MAX(id)+1)
Hope this helps, bye!