How can I make a field default a value with every new record? - mysql

I have an HTML form to insert ($_POST) a new record to MySQL.
I have a field that always needs the value "FC". Do I make this happen in phpMyAdmin or do I insert "FC" at the time when I insert the record via HTML form?

Just perform this query:
ALTER TABLE `tablename` ALTER `fieldname` SET DEFAULT 'FC';
Supposing that you have tablename table and fieldname

MySQL has the option to specify a default value for columns. Edit the column and set default to As defined: and put 'FC' in the field.
For consistency you might also want to insert 'FC' in the form since the default value will not be used if something else is provided.
Or if you really want to limit the value only to 'FC' then why not hardcode it into your query?

Related

how to alter table to add new column date with default value of current date?

I got confused about the alter.
I have an existing table, register and I want to add a this_date column with default value of current date. is it possible by alter? well it has already have data.
It should be okay.
ALTER TABLE ADD COLUMN this_date DATE DEFAULT CURRENT_DATE;
As long as the new column is nullable and/or has a default value, there shouldn't be a problem.
You can also choose where to put the column, use the keyword after:
ALTER TABLE MyTable ADD `MyColumn` DATETIME AFTER `LastColumn`
This wasn't possible for me on MySQL 5.7. It gives me an error every time.
I can do it with a DATETIME field and NOW() as default, but not with CURRENT_DATE.
ALTER TABLE "TableName" ADD "New_Column_Name" TIMESTAMP DEFAULT now();
On MySQL 5.7, I didn't find a way to use CURRENT_DATE or its synonyms as default.
If your application will always provide values in INSERT statements and you only need a way to add a non-null column to existing data and then set values for existing row, you can work around this by providing a fixed default for the non-null date column
ALTER TABLE MyTable ADD COLUMN MyColumn DATE DEFAULT '2020-01-01'
and then update it to CURRENT_DATE
UPDATE MyTable SET MyColumn = CURRENT_DATE

assigning unique default value to existing mysql table

For an existing database and existing table , I want to do something
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
however I'm planning to add a particular user_page_url with unique string. The future handling can be done through php however the recently added column will have NULL value for those old register user.
For example the ID=102 user with username="michael" will have a default value of 102 or default value of "michael"(best), then I am able to do www.test.com/michael with rewriting url to redirect visitor to his homepage
After adding your new column, simply UPDATE your table:
UPDATE {TABLENAME} SET {COLUMNNAME} = username
After you alter the table, do:
UPDATE TableName
SET NewColumn = username
WHERE NewColumn IS NULL

SSIS Inserts not inserting the computed columns

I am using SSIS to insert a Excel file into a Sql Server Table. I believe it uses the Bulk insert, and as a result it doesn't insert into the 'CreationDate' and the 'ModificationDate' columns (both of which are computed columns with getdate() as the default).
Is there a way to get around this problem?
Also, just to be clear - both these date columns are not a part of excel. Here is the exact scenario:
My excel has two columns - code and description. My SQL Server table has 4 columns Code, Description, CreationDate, ModificationDate.
So, when the SSIS copies the data, it copies Code and Description, but the CreationDate and ModificationDate (which are SQL Server Computed Columns) are both empty.
You should use a normal column with a default constraint if you want to log creation
A computed column defined as GETDATE() will change every time you query it.
It is also impossible for a computed column to not be populated
So, assuming you mean "normal column with default", then you need stop sending NULL from SSIS which overrides the default
This is all demonstrated here:
CREATE TABLE #foo (
bar int NOT NULL,
testCol1Null datetime NULL DEFAULT GETDATE(),
testCol1NotNull datetime NOT NULL DEFAULT GETDATE(),
testCol2 AS GETDATE()
);
INSERT #foo (bar, testCol1Null) VALUES (1, NULL);
SELECT * FROM #foo;
WAITFOR DELAY '00:00:00.100';
SELECT * FROM #foo;
WAITFOR DELAY '00:00:00.100';
SELECT * FROM #foo;
DROP TABLE #foo;
Assuming you are using the Bulk Insert Task in SSIS, then you need to set "Keep nulls = off/unchecked" in the options page
You should have a default constraint on the column(s) that specifies get
col1 datetime default getdate()
There should also be an option for the bulk insert KEEPNULLS which should be turned off.
From Bulk Insert on MSDN:
Specifies that empty columns should retain a null value during the bulk-import operation, instead of having any default values for the
columns inserted. For more information, see Keeping Nulls or Using
Default Values During Bulk Import.
KEEPNULLS is also documented: http://msdn.microsoft.com/en-us/library/ms187887.aspx
Put in a Derived Column in your dataflow and populate the two missing columns with the values you want.
The value on a computed column doesn't physically exists on the database, it is calculated every time SQL Server needs to access it, that's why you can't inform a value to it on a insert.
What you need is a default column, which is a column that has a default value that's inserted if you don't inform any other value.
CreationDate datetime default getdate()
ModificationDate datetime default getdate()

REPLACE into keeping a value

I want to make a replace into in a table where cust_id is the primary key, but I do not want to modify the date field. So, a normal insert on this table would look like:
REPLACE INTO emails(cust_id, email, date)
VALUES(55, 'email#email.com', '2011-08-07 00:00');
Now, without having to modify the date field, it would be something such as:
REPLACE INTO emails(cust_id, email, date)
VALUES(55, 'email#email.com', date.value?);
But how do I exactly keep the date value?
Short answer, You can't keep the dates that way. from Mysql documentation
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT. You cannot refer to values from
the current row and use them in the new row
perhaps you want to use http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html instead.
insert ignore will skip insertion if any duplication
if you need to update certain fields ,
you can do
insert into some_table values (...)
on duplicate update email=?;

Access Auto-Increment Value During INSERT INTO Statement

I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.
I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.
Thanks in advance.
I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.
Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:
UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();