Setting conditionally required fields in SQL Server 2008 - sql-server-2008

I need to make conditional requirements for fields. I'm not sure how this looks in SQL. I'm using Management Studio with SQL Server 2008. Essentially I would like a field to become required only when another field has data entered into it. I researched triggers, and I think that's what I need, but I'm not sure what type (DDL, DML, ect.).
For example:
When the user enters a time they must also enter a date, but if no time is entered then no date is required. SQL would send an error and not allow the user to complete the record without entering a date while the time field is filled.
Thanks!

You can use a check constraint.
create table YourTable
(
ID int identity primary key,
DateCol date,
TimeCol time,
constraint ch_DateTime check(
DateCol is not null or
TimeCol is null
)
)
Test with this:
-- null in both columns
insert into YourTable default values
-- values in both columns
insert into YourTable(DateCol, TimeCol) values(getdate(), getdate())
-- value only in DateCol
insert into YourTable(DateCol) values(getdate())
-- value only in TimeCol failes
insert into YourTable(TimeCol) values(GetDate())

Related

How to insert two datetime fields with same server time in mysql?

I have a table with two fields insert_time and update_time.
The type of insert_time is varchar(30) NOT NULL DEFAULT '' while the type of update_time is timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
insert into tableName(inser_time,update_time) values('2017-02-17 20:30:38')
will make the update_time lose its meanings.
So how to make the two fields have a same server time when inserted if not update the Mysql version?
Just set both fields to the same value ?
insert into tableName(inser_time,update_time)
values('2017-02-17 20:30:38','2017-02-17 20:30:38')
EDIT to use current time
insert into tableName(inser_time,update_time)
values(now(), now())
EDIT 2 From mysql manual at:
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_now
Functions that return the current date or time each are evaluated only
once per query at the start of query execution. This means that
multiple references to a function such as NOW() within a single query
always produce the same result.

SSIS default value is not being set when source value in null

Problem:
OLEDB source has null value in phone.
Destination table has Phone NOT NULL DEFAULT 1234567.
OLEDB destination has Keep Nulls unchecked
According to what I read here https://msdn.microsoft.com/en-us/library/ms187887(v=sql.110).aspx
The default value for the column should be inserted if incoming value is NULL.
But it's not happening. And I don't want to do any transformation in SSIS. Can someone help?
In your Data Flow Task, in OLE_DB source, set the data access mode to 'SQL command' and write out a select statement as below
SELECT Column_A
,Column_B
,ISNULL(Phone, 1234567)
,Column_C
,Column_D etc.
FROM Source_Table
you can write CASE statement in SQL command in Data Flow Task:
select
CASE
when PhoneNumber IS NUll then '1234567' else table_name.PhoneNumber END as PhoneNumber,
from table table_name
I believe the answer is that for Keep Nulls option to work the column has to be missing from the data source.
create table #tmpdel
(
a INT NOT NULL default 0,
b INT NOT NULL default 0
)
Insert into #tmpdel(a) values(1) - WORKS
Insert into #tmpdel(a, b) values(1, null) - FAILS

how to store date default values to table.but it takes null values

i am fresher in Sql server 2008.
i create table as:
-- Table structure for [xyz]
-- ----------------------------
DROP TABLE [xyz]
GO
CREATE TABLE [xy] (
[abc] DATETIME DEFAULT GETDATE() NOT NULL
)
in inserted time date values as:2013-08-07 00:00:00.000
i want store time value as it is present time.
You can also use the time stamp for current time for each inserted record.
DROP TABLE [xyz]
GO
CREATE TABLE [xy] (
[abc] DATETIME default CURRENT_TIMESTAMP
)
Try something like this:-
ALTER TABLE myTable ADD CONSTRAINT_NAME DEFAULT GETDATE() FOR myColumn
Your Java code is not including the date - the default value only applies when you do not specify a value - it does not "magically" add the time component to the date you pass in. If you want to add the date you'll have to create an UPDATE/INSERT trigger to add the current time to the date that's pass in.
However, I would just update your Java code (if you can) to include the time.

how can i modify or manipulate this trigger

I'm trying to create a trigger which will capture any event that will occur when I update any column in the table before and after updating, let's say I have 4 columns:
first_name address city country
Let's say I edited first_name lets say Jack to Henk.
It should insert in another table the command (i.e. update) ,time , description but inside the description I want it to write Jack was changed to John by current user(i.e using the current-user () function),if it is a city being updated from Mechinkova to Tostov, it should do the same do with other columns.
I know I want to have to add the concat function inside the trigger, I want it to be like this for example:
DROP TRIGGER IF EXISTS adminpanel.soft//
CREATE TRIGGER adminpanel.soft BEFORE UPDATE ON adminpanel.aggrement
FOR EACH ROW
BEGIN
INSERT INTO adminpanel.aggretrigger(cmd, time, cmd_user, last_name, city) VALUES("INSERT", NOW(), CURRENT_USER(), new.last_name, new.city);
END
//
What you are asking for is an audit trigger. It is very easy to implement.
Let us first slightly modify your main table. Let's add a field id of integer datatype as the primary key to the table, so your table would look like:
tablename
( id integer PK
, first_name varchar
, address varchar
, city varchar
, country varchar
)
Now, you will need a table, say UNIVERSAL_AUDIT_ENTRY table that will store the changes made to the data in your schema.
From what experience I have, I suggest you create this table as follows:
universal_audit_entry
( universal_audit_entryid integer PK
, table_name varchar -- captures the name of the table
, column_name varchar -- captures the name of the column
, entry_type varchar -- captures the event, e.g., 'INSERT' or 'UPDATE'
, primary_key_value integer -- captures, e.g., the value in tblename.id
, from_str varchar -- captures the value that was present before
, to_str varchar -- captures the value that was changed into
, timestamp datetime -- captures the timestamp of the event
, username varchar -- captures the name of user
)
Now with the universal_audit_entry table ready, your trigger should look somewhat like:
CREATE TRIGGER adminpanel.soft
BEFORE UPDATE ON adminpanel.aggrement
FOR EACH ROW
BEGIN
IF UPDATING(first_name) THEN
INSERT INTO universal_audit_entry VALUES
( 123 -- example for universal_audit_entryid
, 'TABLENAME'
, 'FIRST_NAME'
, 'UPDATE'
, new.id
, old.first_name
, new.first_name
, current_timestamp()
, current_user);
END IF;
END;
//
You can use similar logic to audit more columns in the same table and other tables also.
Note:
This code is not tested. I have added it here only for illustration purposes. This code for trigger is not supposed to be used directly.
new and old are the pseudo-records that are generated during an update statement. These records correspond to the rows that are being updated. :new means the row after the update statement runs and :old means the row before the update statement runs. This works in Oracle. Kindly make sure if it works in MySQL also.
EDIT
You can read more about MySQL triggers here. Read more about audit trail here and this SO question.

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()