SQL Server : inserting date returning wrong value - sql

When I try to insert information from another table, it is returning '1900-01-01' from a date column when it should be empty. On the import table the datatype is varchar and on the table I want to insert the information into it is a date datatype. There are some empty values in the EndDate column that should be inserted as empty but it is returning '1900-01-01'
Insert into tblServiceHistory (PersonID, PositionID, CommitteeID,StartDate, EndDate)
Select distinct
PersonID, PositionID, CommitteeID, StartDate, EndDate
From
tblCommitteeOfficers_IMPORT
Where
PersonID is not null
And StartDate is not null
And PositionID is not null
And CommitteeID is not null

Blank strings converted to dates turn in to '1900-01-01'.
e.g. select convert(date,'') returns '1900-01-01'.
You can use nullif() to turn empty strings into null values in your select.
Try this:
Insert into tblServiceHistory (PersonID, PositionID, CommitteeID,StartDate, EndDate)
Select distinct PersonID, PositionID, CommitteeID, nullif(StartDate,''), nullif(EndDate,'')
From tblCommitteeOfficers_IMPORT
Where PersonID is not null
AND nullif(StartDate,'') is not null
AND PositionID is not null
AND CommitteeID is not null

Related

insert date difference in last column

I want to insert date difference of 4th and 5th column in the 6th column but it is giving me error saying column not allowed.
insert into leave25 vALUES (4, 4, 'SICK', TO_DATE('22-AUG-14','DD-MON-YY'), TO_DATE('22-SEP-14','DD-MON-YY'), startdate-enddate)\\
Always specify the column names explicitly in your INSERT statements. It is safer that way.
If you want to avoid writing the dates again, you could select the values from a subquery.
INSERT INTO leave25
(col1,
col2,
col3,
startdate,
enddate,
days)
SELECT t.*,
startdate - enddate
FROM (SELECT 4,
4,
'SICK',
to_date('22-AUG-14', 'DD-MON-YY') as startdate,
to_date('22-SEP-14', 'DD-MON-YY') as enddate
FROM dual) t;
Furthermore, I agree with Aleksej, it is better to have this difference stored as a virtual column rather than a column itself.
You can not do it this way, you need to esplicitly use the values you want to insert:
INSERT INTO leave25
VALUES (
4,
4,
'SICK',
TO_DATE('22-AUG-14', 'DD-MON-YY'),
TO_DATE('22-SEP-14', 'DD-MON-YY'),
TO_DATE('22-SEP-14', 'DD-MON-YY') - TO_DATE('22-AUG-14', 'DD-MON-YY')
Besides, if this column always contains that difference, are you sure you need to store this redundant information?
A different approach could be by using a trigger to populate that column without explicitly giving it a value, but this depends on your environment and your needs.
Use a virtual column:
CREATE TABLE Leave25(
EMPLOYEEID INTEGER
CONSTRAINT LEAVE25__EMPID__FK REFERENCES Employee24,
LEAVEID INTEGER
CONSTRAINT LEAVE25__LEAVEID__PK PRIMARY KEY,
LEAVETYPE VARCHAR2(20)
CONSTRAINT LEAVE25__LEAVETYPE__NN NOT NULL
CONSTRAINT LEAVE25__LEAVETYPE__CHK CHECK (
LEAVETYPE IN 'EARNED', 'SICK'
),
STARTDATE DATE
CONSTRAINT LEAVE25__STARTDATE__NN NOT NULL,
ENDDATE DATE
CONSTRAINT LEAVE25__ENDDATE__NN NOT NULL,
DURATION NUMBER
GENERATED ALWAYS AS ( ENDDATE - STARTDATE ) VIRTUAL
);
And create a sequence to manage the primary key:
CREATE SEQUENCE LEAVE25__LEAVEID__SEQ;
Then you can do:
INSERT INTO leave25 (
EMPLOYEEID, LEAVEID, LEAVETYPE, STARTDATE, ENDDATE
) VALUES (
4, LEAVE25__LEAVEID__SEQ.NEXTVAL, 'SICK', DATE '2014-08-22', DATE '2014-09-22'
)

isnull function does not return correct

When I am using isnull it does not return the '' please see below I have original DOB, isnull used, cast as date.
You would need to convert dob to a char/nchar/varchar/nvarchar type to use isnull() or coalesce() like that.
select isnull(convert(varchar(10),dob,120),'')
if you really would like to return an empty string for the date value, you could try this in a new query window. It creates a table to repoduce your requirement of a null date value and then selects the value before dropping the table.
CREATE TABLE dbo.Test
(
Id INT IDENTITY(1,1) NOT NULL
,Date1 DATE NULL
)
INSERT INTO dbo.Test(Date1) VALUES ('01/01/2017')
INSERT INTO dbo.Test(Date1) VALUES ('01/02/2017')
INSERT INTO dbo.Test(Date1) VALUES (NULL)
INSERT INTO dbo.Test(Date1) VALUES ('01/04/2017')
SELECT * FROM dbo.Test
SELECT Date1 = CASE WHEN date1 IS NULL THEN '' ELSE CAST(DATE1 AS VARCHAR(10)) END from dbo.Test
DROP TABLE dbo.Test
go

Cannot insert the value NULL into column CreationTime

Runtime Exception :
Cannot insert the value NULL into column 'CreationTime', table
'MyTables'; column does not allow nulls. INSERT
fails.
Code:
INSERT INTO [MyTables] (LegacyId, CreationTime)
SELECT DISTINCT
a.[IPLID], a.[inputdate]
FROM
[Legacy].[dbo].[MyTables2] AS a
Can you tell me how to insert custom date like 01/01/2000 when a.[inputdate] is Null ?
just wrap in an ISNULL:
INSERT INTO [MyTables] (LegacyId,CreationTime)
SELECT DISTINCT a.[IPLID],ISNULL(a.[inputdate], '01/01/2000')
FROM [Legacy].[dbo].[MyTables2] as a
Use the ISNULL function.
INSERT INTO [MyTables] (LegacyId,CreationTime)
SELECT DISTINCT a.[IPLID],ISNULL(a.[inputdate], '01/01/2000') FROM [Legacy].[dbo].[MyTables2] as a

SQL Server 2012 Insert DATEDIFF into column trigger whenever a new record is inserted

Table
CREATE TABLE CurrentApplication
(
StartDate datetime NOT NULL,
EndDate datetime NOT NULL,
NoOfDays integer,
StaffID integer NOT NULL,
AppStatus varchar(30) NOT NULL DEFAULT 'PENDING'
)
Trigger
CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
DECLARE #temp INT
SELECT #temp = DATEDIFF(day, EndDate, StartDate)
FROM inserted
INSERT INTO CurrentApplication(NoOfDays) VALUES (#temp)
--SELECT StaffID = inserted.StaffID
--FROM inserted
-- INSERT INTO CurrentApplication(NoOfDays)
-- SELECT Datediff(day, EndDate, StartDate)
-- FROM inserted;
END
Error message:
Msg 515, Level 16, State 2, Procedure InsertNoOfDays, Line 10
Cannot insert the value NULL into column 'StartDate', table
'StaffPortalDB.dbo.CurrentApplication'; column does not allow nulls.
INSERT fails. The statement has been terminated.
What I'm trying to do is I have a table CurrentApplication and I want the NoOfDays column to automatically be populated whenever a user inserts a new row, with the date difference of start day and end day.
IF Sql server
Try inserting some default or dummy values,since its not null column
Some thing like this:
CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
DECLARE #temp INT
SELECT #temp = coalesce(DATEDIFF(day, EndDate, StartDate),0) --Default 0
FROM inserted
INSERT INTO CurrentApplication(NoOfDays) VALUES (#temp)
--SELECT StaffID = inserted.StaffID
--FROM inserted
-- INSERT INTO CurrentApplication(NoOfDays)
-- SELECT Datediff(day, EndDate, StartDate)
-- FROM inserted;
END
It's because your Insert statement is attempting to insert a record but isn't inserting any values into the columns that cannot be empty (StartDate, EndDate, StaffID, AppStatus). For this insert to succeed you need to either change the INSERT statement to insert a value into these columns or change the table schema to allow NULL values.

Pivot String SQL

I am trying to Pivot this table whose name is #salida
IDJOB NAME DATE
1 Michael NULL
1 Aaron NULl
THe result which I want to obtain is
IDJOB DATE NAME1 NAME2
1 NULL Michael Aaron
My code is this
SELECT *
FROM #salida
PIVOT
(
MAX([Name]) FOR [Name] IN ([Name1],[Name2])
) PVT GROUP BY IdJob,Date,Name1,Name2 ;
SELECT * FROM #salida
The result which obtain is
IDJOB DATE NAME1 NAME2
1 NULL NULL NULL
#XabiIparra, see a mock up. you need to partition by the IdJob and then add the columns needed.
DECLARE #salida TABLE(idjob VARCHAR(100),[Name] VARCHAR(100),[DATE] DATE);
INSERT INTO #salida VALUES
(1,'Michael', NULL)
,(1,'Aaron', NULL)
,(2,'Banabas', NULL)
SELECT p.*
FROM
(
SELECT *
,'NAME'+CAST(ROW_NUMBER() OVER(PARTITION BY [idjob] ORDER BY NAME) AS varchar(100)) ColumnName
FROM #salida
)t
PIVOT
(
MAX([Name]) FOR ColumnName IN (NAME1,NAME2,NAME3,NAME4,NAME5 /*add as many as you need*/)
)p;
How about must using aggregation and min() and max()?
select idjob, date, min(name), max(name)
from #salida
group by idjob, date;
SQL tables represent unordered sets, so there is no ordering to the values (unless another column specifies the ordering). So, this is probably the simplest way to get two different values in the same row.