Как добавить дату в таблицу sql
Перейти к содержимому

Как добавить дату в таблицу sql

  • автор:

Как добавить дату в таблицу SQL: простое руководство с примерами кода и советами

Для добавления даты в таблицу в SQL, вы можете использовать команду INSERT. Ниже приведен пример кода, демонстрирующий, как добавить дату в таблицу:

 INSERT INTO название_таблицы (столбец_даты) VALUES ('2022-05-10'); 

В приведенном примере мы используем команду INSERT INTO для вставки значения даты в столбец_даты таблицы. Значение даты должно быть указано в формате ‘год-месяц-день’. Замените «название_таблицы» на имя вашей таблицы и «столбец_даты» на имя соответствующего столбца. Значение даты также должно быть заключено в кавычки.

Детальный ответ

Как добавить дату в таблицу SQL

  1. Определить таблицу, в которую нужно добавить запись.
  2. Указать столбцы, для которых нужно задать значения, включая столбец с датой.
  3. Указать значения для каждого столбца, включая значение даты.
  4. Выполнить команду INSERT INTO.

Пример

Допустим, у нас есть таблица «orders» со следующей структурой:

 CREATE TABLE orders ( id INT PRIMARY KEY, order_date DATE, total_amount DECIMAL(10, 2) ); 

Теперь мы можем добавить новую запись в эту таблицу с помощью следующего SQL-запроса:

 INSERT INTO orders (id, order_date, total_amount) VALUES (1, '2022-01-01', 100.00); 

В этом примере мы указываем значения для столбцов «id», «order_date» и «total_amount». Значение для столбца «order_date» задается в виде строки в формате ‘YYYY-MM-DD’, где YYYY — год, MM — месяц и DD — день.

Если значение даты представлено в другом формате, необходимо преобразовать его в нужный формат перед использованием в SQL-запросе. Например:

 INSERT INTO orders (id, order_date, total_amount) VALUES (2, STR_TO_DATE('01-01-2022', '%d-%m-%Y'), 200.00); 

В этом примере используется функция STR_TO_DATE для преобразования строки ’01-01-2022′ в объект даты, используя формат ‘%d-%m-%Y’. Затем полученное значение даты используется в SQL-запросе.

Также возможно использовать текущую дату в качестве значения для столбца с помощью функции CURRENT_DATE. Пример:

 INSERT INTO orders (id, order_date, total_amount) VALUES (3, CURRENT_DATE, 300.00); 

При выполнении этого SQL-запроса в столбец «order_date» будет автоматически добавлена текущая дата.

Надеюсь, эта статья помогла вам понять, как добавить дату в таблицу SQL. Помните, что корректное указание формата даты и правильное преобразование значений могут быть важными для успешного добавления данных в таблицу.

Как добавить дату в таблицу sql

Summary: in this tutorial, you will learn about MySQL DATETIME data type and how to use some handy functions for manipulating DATETIME effectively.

Introduction to MySQL DATETIME data type

You use MySQL DATETIME to store a value that contains both date and time. When you query data from a DATETIME column, MySQL displays the DATETIME value in the following format:

By default, DATETIME values range from 1000-01-01 00:00:00 to 9999-12-31 23:59:59 .

A DATETIME value uses 5 bytes for storage. In addition, a DATETIME value can include a trailing fractional second up to microseconds with the format YYYY-MM-DD HH:MM:SS[.fraction] e.g., 2015-12-20 10:01:00.999999 . When including the fractional second precision, DATETIME values require more storage as illustrated in the following table:

Fractional Seconds Precision Storage (Bytes)
0 0
1, 2 1
3, 4 2
5, 6 3

For example, 2015-12-20 10:01:00.999999 requires 8 bytes, 5 bytes for 2015-12-20 10:01:00 and 3 bytes for .999999 while 2015-12-20 10:01:00.9 requires only 6 bytes, 1 byte for the fractional second precision.

Note that before MySQL 5.6.4, DATETIME values requires 8 bytes storage instead of 5 bytes.

MySQL DATETIME vs. TIMESTAMP

MySQL provides another temporal data type that is similar to the DATETIME called TIMESTAMP .

The TIMESTAMP requires 4 bytes while DATETIME requires 5 bytes. Both TIMESTAMP and DATETIME require additional bytes for fractional seconds precision.

TIMESTAMP values range from 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC . If you want to store temporal values that are beyond 2038, you should use DATETIME instead of TIMESTAMP .

MySQL stores TIMESTAMP in UTC value. However, MySQL stores the DATETIME value as is without timezone. Let’s see the following example.

First, set the timezone of the current connection to +00:00 .

Next, create a table named timestamp_n_datetime that consists of two columns: ts and dt with TIMESTAMP and DATETIME types using the following statement.

Then, insert the current date and time into both ts and dt columns of the timestamp_n_datetime table,

After that, query data from the timestamp_n_datetime table.

MySQL DATETIME vs TIMESTAMP

Both values in DATETIME and TIMESTAMP columns are the same.

Finally, set the connection’s time zone to +03:00 and query data from the timestamp_n_datetime table again.

MySQL DATETIME vs TIMESTAMP timezone changes

As you can see, the value in the TIMESTAMP column is different. This is because the TIMESTAMP column stores the date and time value in UTC when we changed the time zone, the value of the TIMESTAMP column is adjusted according to the new time zone.

It means that if you use the TIMESTAMP data to store date and time values, you should take a serious consideration when you move your database to a server located in a different time zone.

MySQL DATETIME functions

The following statement sets the variable @dt to the current date and time using the NOW() function.

To query the value of the @dt variable, you use the following SELECT statement:

MySQL DATE function

To extract the date portion from a DATETIME value, you use the DATE function as follows:

This function is very useful in case you want to query data based on a date but the data stored in the column is based on both date and time.

Let’s see the following example.

Suppose you want to know which row created on 2015-11-05 , you use the following query:

It returns no rows.

This is because the created_at column contains not only date but also time. To correct it, you use the DATE function as follows:

MySQL DATETIME - DATE function

It returns one row as expected. In case the table has many rows, MySQL has to perform a full table scan to locate the rows that match the condition.

MySQL TIME function

To extract the time portion from a DATETIME value, you use the TIME function as the following statement:

MySQL YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE and SECOND functions

To get the year, quarter, month, week, day, hour, minute, and second from a DATETIME value, you use the functions as shown in the following statement:

MySQL DATETIME - datetime functions

MySQL DATE_FORMAT function

To format a DATETIME value, you use the DATE_FORMAT function. For example, the following statement formats a DATETIME value based on the %H:%i:%s — %W %M %Y format:

MySQL DATETIME - DATE_FORMAT function

MySQL DATE_ADD function

To add an interval to a DATETIME value, you use DATE_ADD function as follows:

MySQL DATETIME - DATE_ADD function

MySQL DATE_SUB function

To subtract an interval from a DATETIME value, you use DATE_SUB function as follows:

MySQL DATETIME - DATE_SUB function

MySQL DATE_DIFF function

To calculate a difference in days between two DATETIME values, you use the DATEDIFF function. Notice that the DATEDIFF function only considers the date part of a DATETIME value in the calculation.

See the following example.

First, create a table named datediff_test that has one column whose data type is DATETIME .

Second, insert some rows into the datediff_test table.

Third, use the DATEDIFF function to compare the current date and time with the value in each row of the datediff_test table.

MySQL DATETIME - DATEDIFF Example

In this tutorial, you have learned about MySQL DATETIME data type and some useful DATETIME functions.

How to insert date values into table

How can I insert into table with different input using / ,with date datatype?

I’m using oracle 10g.

7 Answers 7

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format ‘YYYY-MM-DD’ and is NLS independent.

Как добавить дату в таблицу sql

Whenever we work with databases, we find that almost every single table contains a Date column. After all, the date of the data plays an important role while analyzing it. Storing dates in a specific or understandable format is very important. In this article, we are going to learn how we can specify a Date format on SQL Server.

Let’s create our demo database and table.

Step 1: Create a database

Use the following command to create a database.

Query:

Step 2:Use database

Query:

Step 3: Table definition

We have the following GFG_user table in the database.

Query:

Output:

Here, we have created a column named Dt_FORMATTED where we are going to save our formatted Date.

Now, we see the CONVERT() function. The CONVERT() function simply converts a value of any type into a specified datatype.

Syntax:

By using this function, we are casting the string to a date. In the place of style argument, we have mentioned ‘104’. It is a numeric code to specify the date format.

Check this table to see different codes used for different formats:

With century
With century
Standard
Input/Output

Default for datetime

Here, We have mentioned only the 10 most used formats.

Step 4: Insert values

The following command is used to insert values into the table.

Query:

In this query, we are using the DATEFORMAT setting.

Syntax:

When we are inserting the string, the server will try to convert the string to date before inserting it into the table. As it cannot tell if we are putting the month before the date or the date before the month. For example, suppose you are trying to insert 06.07.2000. The server is unable to detect if the date is the 6th of July or it is the 7th of June. Though it uses the localization settings of the user account that is operating to figure that out not mentioning the DATEFORMAT might give you an error as most of the times the account that is running the operation is set to USA format, that is – Month Day Year (mdy).

The error was caused because we wanted to save it as dmy, not mdy. However, using DATEFORMAT will help you to get rid of it.

Output:

We are done with our table, now let’s check if we are getting our desired output or not.

Step 5: View data of the table

Query:

Output:

We have successfully got our German format Date in the Dt_FORMATTED column.

Another approach to insert date in database:

We can also insert date using ‘to_date’ function in sql. The following syntax can be used:

Format of date can be of different types such as: ‘dd-mm-yyyy’, ‘yyyy-mm-dd’, ‘mm-dd-yyyy’.

Add and Subtract Dates using DATEADD in SQL Server

Date manipulation is a common scenario when retrieving or storing data in a Microsoft SQL Server database. There are several date functions (DATENAME, DATEPART, DATEADD, DATEDIFF, etc.) that are available and in this tutorial, we look at how to use the DATEADD function in SQL queries, stored procedures, T-SQL scripts, etc. for OLTP databases as well as data warehouse and data science projects.

Solution

The DATEADD function simply allows you to add or subtract the specified number of units of time to a specified date/time value.

SQL Server DATEADD Function

The T-SQL syntax of the DATEADD function is as follows:

— Syntax to add 5 days to September 1, 2011 (input date) the function would be
DATEADD(DAY, 5, ‘9/1/2011’)

— Syntax to subtract 5 months from September 1, 2011 (input date) the function would be
DATEADD(MONTH, -5, ‘9/1/2011’)

Using DATEADD Function and Examples

  1. Add 30 days to a date SELECT DATEADD(DD,30,@Date)
  2. Add 3 hours to a date SELECT DATEADD(HOUR,-3,@Date)
  3. Subtract 90 minutes from date SELECT DATEADD(MINUTE,-90,@Date)
  4. Check out the chart to get a list of all options

Date Formats and Units of Time

A thing to note is that the date format can be any date format that SQL Server recognizes such as:

  • 9/1/2011
  • 9/1/2011 12:30
  • 9/1/2011 12:30:999
  • 2011-09-01
  • 2011-09-01 12:30
  • etc.

Here are the units of time, the SQL Server versions in which they can be used, and abbreviations that can be used instead of the full unit of time name:

Units of Time Available in SQL Server
Unit of time 2000/2005 2008 + Abbreviations
NANOSECOND No Yes ns
MICROSECOND No Yes mcs
MILLISECOND Yes Yes ms
SECOND Yes Yes ss, s
MINUTE Yes Yes mi, n
HOUR Yes Yes hh
WEEKDAY Yes Yes dw, w
WEEK Yes Yes wk, ww
DAY Yes Yes dd, d
DAYOFYEAR Yes Yes dy, y
MONTH Yes Yes mm, m
QUARTER Yes Yes qq, q
YEAR Yes Yes yy, yyyy

The table above reveals that there are some units of time that cannot be used with earlier versions of SQL Server. SQL Server 2008 and later introduced new date/time data types: DATETIME2, TIME, and DATETIMEOFFSET. The MICROSECOND and NANSECOND units of time were introduced as well, but cannot be used in earlier versions of SQL Server. Another thing to keep in mind is that you can’t use the seconds unit of time with the DATE data type.

SQL Server DATEADD Function Examples

For all of these Transact-SQL examples, the parameter @Date = «2011-09-23 15:48:39.2370000», which we consider our current date. We can test the SQL commands as follows:

Examples of Using the DATEADD Function
Unit of time Query Result
NANOSECOND SELECT DATEADD(NANOSECOND,150000,@Date) 2011-09-23 15:48:39.2371500
MICROSECOND SELECT DATEADD(MICROSECOND,150000,@Date) 2011-09-23 15:48:39.3870000
MILLISECOND SELECT DATEADD(MILLISECOND,1500,@Date) 2011-09-23 15:48:40.7370000
SECOND SELECT DATEADD(SECOND,1500,@Date) 2011-09-23 16:13:39.2370000
MINUTE SELECT DATEADD(MINUTE,15,@Date) 2011-09-23 16:03:39.2370000
HOUR SELECT DATEADD(HOUR,-3,@Date) 2011-09-23 12:48:39.2370000
WEEKDAY SELECT DATEADD(WEEKDAY,-2,@Date) 2011-09-21 15:48:39.2370000
WEEK SELECT DATEADD(WEEK,4,@Date) 2011-10-21 15:48:39.2370000
DAY SELECT DATEADD(DD,4,@Date) 2011-09-27 15:48:39.2370000
DAYOFYEAR SELECT DATEADD(DY,14,@Date) 2011-10-07 15:48:39.2370000
MONTH SELECT DATEADD(MM,-4,@Date) 2011-05-23 15:48:39.2370000
QUARTER SELECT DATEADD(Q,-2,@Date) 2011-03-23 15:48:39.2370000
YEAR SELECT DATEADD(YYYY,-5,@Date) 2006-09-23 15:48:39.2370000
Example 1

A practical use of DATEADD is to return a user-friendly length of time that has elapsed between two times, like how long it takes for a student to complete an exam.

Below we are also using the DATEDIFF function to find the difference between the start and end time in seconds, then adding the number of seconds to 01/01/1900, which can be represented as a 0.

Example 2

Another use would be when retrieving data based on a period. The procedure could pass in a start date and a number of days to retrieve data.

Next Steps
  • Keep in mind that the NANOSECOND and MICROSECOND units of time can only be used with SQL Server 2008 and later
  • Also keep in mind that there is more than one way to execute a query and get the same results. There will be tips in the future that will discuss other options
  • Read about the DATEADD function
  • Learn more about the date and time data types available in SQL Server 2008 and later.
  • For other date formats refer to this tip: Date and Time Conversions Using SQL Server
  • Learn the options for the SQL current date including GETDATE(), CURRENT_TIMESTAMP, SYSDATETIME(), etc.
  • Check out the following tutorials
    • Date and Time SQL Functions with Examples
    • Determine Date and Time Parts with SQL DATEPART and DATENAME Functions

    get scripts

    next tip button

    About the author

    Tim Cullen has been working in the IT industry since 2003 and currently works as a SQL Server Reports Developer.

    Article Last Updated: 2021-07-19

    Comments For This Article

    can you just pass the interval value for each record, instead of hard coding the value.

    SELECT DATE_ADD(base_date, INTERVAL frequency DAY);

    As you can see is that all the frequency days are not the same. I cant use «INTERVAL» because Interval is a fix amount of days.. When you add say 25 days to all the dates.

    This article is for how to do this in SQL Server.

    Check out this one for MySQL — https://www.w3schools.com/SQl/func_mysql_date_add.asp

    Hi Louis, you are correct. A positive number to add and a negative number to subtract. The examples above show both adding and subtracting from the date which is what is done in the HOUR example.

    Add 3 hours to a date SELECT DATEADD(HOUR,-3,@Date)

    Shouldn’t this be +3?

    I have an ERP system that generates time records (Oracle table) that are then extracted via SQL and interfaced to another system for payroll processing.

    In short what is happening is scanning employee badge creates two records. one is the basic time stamp and the other (identical time stamp also) but referencing the account OVH which is unaccountable time. This identical timestamping is considered a duplicate in the upstream system and they delete the OVH record. The upstream SME’s say other teams add a milli second to the record for OVH to ensure no duplicate. I need some help in how to select from the tables but add the millisecond. Any help would be really appreciated. Thanks and my yahoo account is best to respond to.

    Code snippet where st_time is the record we would want to modify and have 1 millisecond additional:

    select etg.etg_rcd_ak, sys.user_id user_id, sys.sdf_sysur_005 starsID,
    sys.sdf_sysur_004 home_div,
    ‘LABOR’ trans_type,
    ‘ ‘ scan_type,
    lbh.lbh_auto_key batch_header_auto_key,
    ‘1’ batch_code,
    ‘1’ charge_qty,
    to_char(wtl.start_time,’YYYYMMDD’)st_date,
    to_char(wtl.start_time,’HH24:MI:SS’) st_time,
    » clock_record_autokey,
    substr(wtl.machine,-7) dev_used,
    to_char(wtl.wtl_auto_key) labor_record_autokey,
    woo.si_number, to_char(wot.sequence) task
    from wo_task_labor wtl, sys_users sys, wo_task wot, wo_operation woo, etg_labor etg, labor_batch_header lbh, labor_batch_detail lbd
    where sys.sysur_auto_key = wtl.sysur_auto_key
    and etg.wtl_auto_key = wtl.wtl_auto_key
    and wtl.wot_auto_key = wot.wot_auto_key
    and wot.woo_auto_key = woo.woo_auto_key
    and etg.lbd_auto_key is not null
    and etg.lbd_auto_key = lbd.lbd_auto_key
    and lbd.lbh_auto_key = lbh.lbh_auto_key
    and etg.sent = ‘F’

    how can I subtract 3 or more datetime value in SQL report expression

    ex: Fields!TimeOut.value- Fields!TimeIn.value- Fields!Breaktime.value

    when I try this it gave me at error. only 2 fields accepting. like below

    if I add the third one it gives me an error.

    hi,how am i going to select the records per week? example i want to select the 1st week of july where the start date is sunday?this is for my weekly report but i dont know how to start it. i can post my code here for getting the records daily if it is possible to use for weekly:

    Dim dt As Date = DateTimePicker1.Text

    If ComboBox1.Text = «Central Reservation Report» Then

    If RadioButton1.Checked = True Then

    Dim rpt As New rsvD() ‘The report you created.

    Dim MyCommand As New SqlCommand()

    Dim myDS As New DScentralrsv() ‘The DataSet you created.

    Dim myDA As New SqlDataAdapter()

    Dim cn As New SqlConnection(ConnectString())

    MyCommand.CommandText = «Select irsno,date,industry,totalamount from maintable where date=’» + dt + «‘»

    MyCommand.CommandText = «Select irsno from roomtbl»

    Catch Excep As Exception

    MessageBox.Show(Excep.Message, «Error», MessageBoxButtons.OK, MessageBoxIcon.Error)

    Good evening, Martin:

    Can you give me a little more clarification? I’m not sure of what you ultimately want to do.

    Hi, im a new guy in the sql programming so please i need your help, i have a view with the code attached, my problem is that i must to change the date (2013-05-30) by the date of the system and i dont know how can you help me? Thanks

    SELECT GETDATE() as MYDATE,debcode AS Relation, DebtorNumber AS OffsetNumber, ci.cmp_name AS OffSetName, (CASE WHEN bt.Type = ‘S’ THEN bt.ValueDate ELSE bt.InvoiceDate END)
    AS InvDate, bt.DueDate AS DueDate, bt.InvoiceNumber, bt.SupplierInvoiceNumber, (CASE WHEN bt.AmountDC > 0 AND
    bt.Type = ‘W’ THEN bt.AmountDC ELSE (CASE WHEN bt.Type = ‘S’ AND bt.AmountDC < 0 THEN — bt.AmountDC ELSE NULL END) END) AS Debit,
    (CASE WHEN bt.AmountDC < 0 AND bt.Type = ‘W’ THEN — bt.AmountDC ELSE (CASE WHEN bt.Type = ‘S’ AND bt.AmountDC >0 THEN bt.AmountDC ELSE NULL END)
    END) AS Credit, ROUND((CASE WHEN DATEDIFF(dd, bt.DueDate, ) BETWEEN 0 AND 30 AND
    bt.Type = ‘W’ THEN bt.AmountDC ELSE (CASE WHEN DATEDIFF(dd, bt.ValueDate, ) BETWEEN 0 AND 30 AND
    bt.Type = ‘S’ THEN — bt.AmountDC ELSE NULL END) END), 2) AS T1, ROUND((CASE WHEN DATEDIFF(dd, bt.DueDate, ) BETWEEN 31 AND 60 AND
    bt.Type = ‘W’ THEN bt.AmountDC ELSE (CASE WHEN DATEDIFF(dd, bt.ValueDate, ) BETWEEN 31 AND 60 AND
    bt.Type = ‘S’ THEN — bt.AmountDC ELSE NULL END) END), 2) AS T2, ROUND((CASE WHEN DATEDIFF(dd, bt.DueDate, ) BETWEEN 61 AND 90 AND
    bt.Type = ‘W’ THEN bt.AmountDC ELSE (CASE WHEN DATEDIFF(dd, bt.ValueDate, ) BETWEEN 61 AND 90 AND
    bt.Type = ‘S’ THEN — bt.AmountDC ELSE NULL END) END), 2) AS T3, ROUND((CASE WHEN DATEDIFF(dd, bt.DueDate, ) > 90 AND
    bt.Type = ‘W’ THEN bt.AmountDC ELSE (CASE WHEN DATEDIFF(dd, bt.ValueDate, ) > 90 AND bt.Type = ‘S’ THEN — bt.AmountDC ELSE NULL END)
    END), 2) AS T4, (CASE WHEN bt.Type = ‘W’ THEN bt.AmountDC ELSE — bt.AmountDC END) AS AmountDC, cc.ClassificationID AS Classification, bt.Description,
    bt.EntryNumber, (CASE WHEN bt.Type = ‘W’ THEN bt.AmountTC ELSE — bt.AmountTC END) AS AmountT

    f the year is more than 2063 then you can’t do your calculations, dont ask me why or how but thats what i have observed.

    Похожие публикации:

    1. Sql server management studio как поменять язык
    2. Sql shell psql как пользоваться
    3. Sql как выбрать базу данных
    4. Sql как найти символ в строке

    Автоматическая вставка текущей даты и времени при добавление записи в таблицу

    Цель: Нужно реализовать автоматическую вставку текущей даты и времени при добавлении записи в таблицу (IDStudent).

     public class Students < [Key] [HiddenInput(DisplayValue = false)] public int StudentsId < get; set; >public string IDStudent < get; set; >public string Name < get; set; >public string Notes < get; set; >public string datetime < get; set; >/* **. ** */ > 

    Данные в db уже есть и нужно только добавить или создать новый IDStudent.

     @using (Html.BeginForm()) < @Html.TextBoxFor(m =>m.IDStudent, new < @class = "form-control">) @Html.ValidationMessage("IDStudent") 
    >

    При сохранении IDStudent автоматически сохранялась дата и время. От куда брать дату и время? В контроллере и предавать ее строкой в базу данных или через sql? Как это реализовать и как проще? Только познаю программирование и mvc. Заранее Благодарю за ответ!

    Как вставить автоматически дату(системную) в таблицу?

    Author24 — интернет-сервис помощи студентам

    Подскажите, пожалуйста, как вставить дату(текущего дня), то есть, чтобы при добавлении новой строки, дата автоматически добавлялась в таблицу в колонку Date_sup ?

    1 2 3 4 5 6 7
    CREATE TABLE Suppliers ( id_sup int not NULL primary key identity (1,1), Date_sup datetime not NULL, . Contract_number_sup char(150), Supplers_name_sup char(150) );

    94731 / 64177 / 26122
    Регистрация: 12.04.2006
    Сообщений: 116,782
    Ответы с готовыми решениями:

    Как через SQL запрос определить системную дату и время?
    как через SQL запрос определить системную дату и время? эту надо потом забить в поле.

    Как вставить текущую дату через SQL.
    Как вставить дату в поле Date MS Access через запрос SQL. Если использовать insert into .

    Как создать таблицу, чтобы одно из полей автоматически увеличивалось на 1
    Как создать таблицу, чтобы одно из полей автоматически увеличивалось на 1. Например нужно создать.

    Как автоматически создавать третью (связующую) таблицу при связи многие ко многим ?
    Например, есть 3 таблицы Subject , Teacher, Teacher_Subject. Teacher_Subject — связующая таблица.

    194 / 193 / 17
    Регистрация: 07.11.2010
    Сообщений: 477
    Использовать триггер

    1 2 3 4 5 6 7 8
    CREATE TRIGGER [dbo].[tr_date] ON [dbo].[Suppliers] FOR INSERT AS BEGIN SET NOCOUNT ON; UPDATE T SET T.Date_sup = getdate() FROM [dbo].[Suppliers] T JOIN inserted i ON T.id = i.id END

    134 / 119 / 0
    Регистрация: 30.06.2010
    Сообщений: 221

    1 2 3 4 5 6
    CREATE TABLE Suppliers ( id_sup INT NOT NULL PRIMARY KEY IDENTITY (1,1), Date_sup DATETIME NOT NULL DEFAULT getdate(), Contract_number_sup CHAR(150), Supplers_name_sup CHAR(150) );

    87844 / 49110 / 22898
    Регистрация: 17.06.2006
    Сообщений: 92,604
    Помогаю со студенческими работами здесь

    Как с помощью ASP вставить текущую дату в таблицу MS Access 97?
    Как с помощью ASP вставить текущую дату в таблицу MS Access 97, если формат поля в таблице.

    Как считать системную дату?
    Есть база данных с днями рождения всех студентов группы и преподавателей. Сделанная через case.

    Как определить системную дату?
    Как найти текущую системную дату на компе, а именно год и записать в переменную типа int?

    Как вставить текущую дату в форму и в таблицу через выражения при добавлении новой записи
    Как вставить текущую дату в форму и в таблицу через выражение(построитель выражений) при добавлении.

    Или воспользуйтесь поиском по форуму:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *