Adding sysdate and user name in the field

  • Hi all,

    In the MS SQL server’s table\Validate field, Is there a way to automate the following task in such as soon as users click on the filed?

    Here is what we need:

     To insert today’s data and time and username in the validate field.

    Such as:

    12/02/2004:12:30:05 ersonName>JimersonName>

    Thanks in advance.

     

    Abrahim

     

     

  • create tabel mytable(

    mybunch_of_columns ....

    , tsInserted datetime not null default getdate()

    , UserInserted varchar(50) not null default suser_sname()

    ) ...

    This makes you don't have to change your insert-script because if the columns are not mentioned for insert sqlserver will apply the default-constraint.

     

    Johan

    Learn to play, play to learn !

    Dont drive faster than your guardian angel can fly ...
    but keeping both feet on the ground wont get you anywhere :w00t:

    - How to post Performance Problems
    - How to post data/code to get the best help[/url]

    - How to prevent a sore throat after hours of presenting ppt

    press F1 for solution, press shift+F1 for urgent solution 😀

    Need a bit of Powershell? How about this

    Who am I ? Sometimes this is me but most of the time this is me

  • The previous post has many advantages; however, it has one drawback. The malicious user can over ride the defaults with data. The only way to ensure data that is accurate as SQL server can generate is to use triggers. The context_info data is set so I can disable a very similar trigger for modification. The approach is slower and does require modification of any insert statements.

     

    create trigger myTable_Insert_Trg on [dbo].[myTable]

      after insert as begin

                      set context_info 0x01

                      update myTable set

                            CreateDate= GetDate() ,

                            Creator=User_id()

                        where myPrimaryKey=(select myPrimaryKey from inserted)

                      set context_info 0x00

                      end

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply