If NULL pass blank instead - sql

I need to push data from a SQL table to an intermediate table in JDE. I am having issues with NULLS not being passed as blanks. How can I replace any NULL values with blanks into JDE.
This is my statement to update my SQLDB:
Insert into AP_InvoiceHeader
(DocID,[Vendor Name],[Vendor No],[Invoice Number],[Invoice Date],[PO Number],[Invoice Amount],MVRUploadDate,DocName)
values ({sys DocID},'{doc Vendor Name}','{doc Vendor No}','{doc Invoice Number}','{doc Invoice Date}','{doc PO Number}','{doc Invoice Amount}',GETDATE(),(select DocName from document where Docid={sys DocID}))
With this statement, if there isn't a value to pass, it shows up as NULL in SQL. Would it be better to do a NULL to blank conversion into my SQLDB or should it be done when I update the intermediate table?
This is my statement that selects from my SQLDB and inserts it into the intermediate JDE table. I know what I want to do but, I am not sure how to write it. I would like to say, if [PO Number]=NULL change it to blank. Is there a way that it can check for any NULLS and replace all NULLS with blanks?
INSERT INTO [MyJDE_VENDOR].[PS_DEV].[TESTDTA].[F55METAA] ([MVMLNM],[MVAN8],[MVVR01],[MVVINV],[MVDIVJ],[MVAG],[MVTRDJ],[MVRMK3],[MV55MV],[MVUMEMO1])
SELECT [Vendor Name],[Vendor No],[PO Number],[Invoice Number],cast('1'+ RIGHT(CAST(YEAR(cast([Invoice Date] as date)) AS CHAR(4)),2) + RIGHT('000' + CAST(DATEPART(dy, cast([Invoice Date] as date)) AS varchar(3)),3) as int) as [Invoice Date],[Invoice Amount]*100,cast('1'+ RIGHT(CAST(YEAR(cast([MVRUploadDate] as date)) AS CHAR(4)),2) + RIGHT('000' + CAST(DATEPART(dy, cast([MVRUploadDate] as date)) AS varchar(3)),3) as int) as [MVRUploadDate],[ProcessedFlag],[DocID],[DocName]
FROM [MyDataBase].[dbo].[AP_InvoiceHeader] WHERE DocID ={sys DocID}

The standard SQL function is coalesce(). It is a bit unclear which fields you want this for:
INSERT INTO [MyJDE_VENDOR].[PS_DEV].[TESTDTA].[F55METAA] ([MVMLNM],[MVAN8],[MVVR01],[MVVINV],[MVDIVJ],[MVAG],[MVTRDJ],[MVRMK3],[MV55MV],[MVUMEMO1])
SELECT coalesce([Vendor Name], ''),
coalesce([Vendor No], ''),
coalesce([PO Number], ''),
coalesce([Invoice Number], '')
coalesce(cast('1'+ RIGHT(CAST(YEAR(cast([Invoice Date] as date)) AS CHAR(4)),2) + RIGHT('000' + CAST(DATEPART(dy, cast([Invoice Date] as date)) AS varchar(3)),3) as int) as [Invoice Date],[Invoice Amount]*100,cast('1'+ RIGHT(CAST(YEAR(cast([MVRUploadDate] as date)) AS CHAR(4)),2) + RIGHT('000' + CAST(DATEPART(dy, cast([MVRUploadDate] as date)) AS varchar(3)),3) as int) , '') as [MVRUploadDate],
coalesce([ProcessedFlag], ''),
coalesce([DocID], ''),
coalesce([DocName], '')
FROM [MyDataBase].[dbo].[AP_InvoiceHeader]
WHERE DocID ={sys DocID}

In MS SQL SERVER, if you are specifically targeting nulls then you can use the isnull function.
isnull(column,'')

Related

How to solve this SQL WHERE (date and exception) Syntax Error?

Could you take a look at the query below please? I tried to convert my access table into a SQL query with very little knowledge (for now).
The last line seems to be wrong when I execute it.
USE [idb_datastore]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[idb_dataSTORESQLTesting]
AS
IF OBJECT_ID( 'idb_datastore.dbo.[Testing]','U' ) IS NOT NULL
DROP TABLE idb_datastore.dbo.[Testing];
SELECT dbo.REC_HDR.F91 AS [PO Number],
hd.F1032 AS [Trs Number],
hd.F76 AS [Order Date],
hd.F27 AS [Vendor ID],
hd.F334 AS [Vendor Name],
hd.F1246 AS [Delivery Date],
hd.F1127 AS [Operator Short Name],
hd.F1068 AS State,
hd.F1067 AS Status
FROM SMSSERVER01.STORESQL.dbo.REC_HDR hd
WHERE hd.F91 Is Not Null AND hd.F76 >= Convert(datetime, ’2017/01/01’ ) AND
hd.F1068 NOT like ’Voided’
Here
SQL datetime format is yyyy-mm-dd hh:mm:ss
change the final line to this
Convert(datetime, '2017-01-01' )
Change the where sentence to this
WHERE hd.F91 Is Not Null
AND hd.F76 >= CONVERT(DATETIME, '03/13/2013', 101)
AND hd.F1068 NOT like '%Voided%'

CONCAT columns without sub-query SQL Server

I was looking to see if there was a better approach to this query
The date field is formatted - 06-03-2018
I need a column that looks like e.g. Mar-18
e.g
SELECT
CONCAT(P.[Month] + '-', p.[Year]) AS [Month-Year]
FROM
(
SELECT
left(datename(MONTH,[Date]),3) AS [Month]
,right(YEAR([Date]),2) AS [Year]
FROM
Table1
)P
This gives me the result i want but i was wondering if there was anyway to get the same result without a sub-query. Thanks
Why not just format the date as
select format(convert(date, '06-03-2018', 103), 'MMM-yy')
The query you've provided isn't valid, you need a comma (,) between column declarations (which you're missing.
Anyway, the query can be simplified to:
SELECT LEFT(DATENAME(MONTH,[Date]),3) + '-' + RIGHT(YEAR([Date]),2) AS [Month-Year]
FROM Table1;
I haven't used CONCAT here, as there is no need (as either both values will be NULL or have a value).
You Can Do the concatenation directly
SELECT
CAST(LEFT(datename(MONTH, [Date]), 3) AS VARCHAR(20))
+'-'+
CAST(RIGHT(YEAR([Date]), 2) AS VARCHAR(20))
FROM Table1;

(Date Difference Finder) Pass result of a select query into another select query inside if-else loop

I am trying to finding date difference between today's date and given date in the table.Some rows has 1 date while others has 2 dates (take earlier date). I tried with dynamic variable and temp table but still not working
else
begin
SELECT * INTO #result2
FROM
(
declare #t date
set #t = '
select SUBSTRING(Availability, PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', [Availability]), 11) as [Date Part] from [ScrappedData_Regina] '
-- extracts date part from a column
select distinct [Product Name],[SKU],DATEDIFF(day,cast(#t as date),cast(GETDATE() as date)) as [Delivery Date] from ScrappedData_Regina
) -- i want to pass the date part in this select statement
The first query will give result as
And I want the same result for second query too for two dates case.
Finally combine both the result in a table
I think you should be able to do that in one query (if I understand what you're trying to do). Remove the first query and replace the second one with this:
SELECT DISTINCT [Product Name],
[SKU],
DATEDIFF(DAY, CAST(
SUBSTRING(Availability,
PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', [Availability]), 11) AS DATE),
CAST(GETDATE() AS DATE)
) AS [Delivery Date]
FROM ScrappedData_Regina

SQL Server Increase script performance by finding another way of doing the same type of join

I have a script which for a given time period returns only the rows in question and duplicates any row which took over 60 seconds to send. This is achieved by doing the following join:
FROM Table t
INNER JOIN CTE_DayHourMinutes dhm ON
Calculate_Date >= t.[Start Date]
AND
dhm.Calculate_Date <= t.[End Date]
For each record in table t where it matches with the YYYY-MM-DD HH-MM-SS of the calculated date it joins together. The only issue with this is it takes 10 or so minutes to return 100 records. Eventually, the script shall be used internally on a system which could potentially have thousands if not millions of rows as we shall be looking to pull through three months’ worth of data.
I should also mention, I have tested the rest of the script and every works fine and with no performance issues when runnign the necessary CTE's and other sections. The only issue is the way I am trying to do the above join and the number of rows it has to check, which at present takes far too long.
As such I am at a loss as to how the above could be achieved in a similar way but improve the performance of the script.
'
DECLARE
#startDate DateTime
, #currentDate DateTime
/* Demo System */ SET #currentDate = '2014-04-26'
SET #startDate = DATEADD(day, -10 , #CurrentDate)
-- Create a list of Days (depending on the month in question)
-------------------------------------------------------------
; WITH CTE_dayList as
(
SELECT #startDate as cal_day
union all
SELECT DATEADD(DAY , 1, d1var.cal_day) as cal_day FROM CTE_daylist d1var
WHERE DATEADD(DAY , 1, d1var.cal_day) <= #currentDate
)
-- Create a list of hours 0 - 23 (24 hours)
-------------------------------------------
, CTE_hourList as
(
SELECT 0 as cal_hour
union all
SELECT h1var.cal_hour + 1 as cal_hour FROM CTE_hourList h1var
WHERE h1var.cal_hour + 1 <= 23
)
-- Create a list of minutes 0 - 59 (1 hour)
-------------------------------------------
, CTE_minuteList as
(
SELECT 0 as cal_minute
union all
SELECT m1var.cal_minute + 1 as cal_minute FROM CTE_minuteList m1var
WHERE m1var.cal_minute + 1 <= 59
)
-- Create a day , hour and minnute -- cross join the hour and minute onto each day between the two dates.
, CTE_DayHourMinutes as
(
SELECT
-- cast the cal_day (date) with the hours and minute, to create a date and time.
CAST(CAST(cal_day AS VARCHAR) + CAST(CAST(cal_hour as VARCHAR) + ':' + CAST(cal_minute AS VARCHAR) AS DATETIME) AS DATETIME) AS Calculate_Date
FROM CTE_dayList
CROSS JOIN
(SELECT cal_hour , cal_minute FROM CTE_hourList CROSS JOIN CTE_minuteList) DHMList)
-- create transmission end date and time ( required for the join in the main select statement )
, CTE_Text RF as
(
SELECT
H.ObjectGuid AS Transmission_ID
, CAST(H.[TRDateTime] AS DateTime) AS [Transmission Start Date]
, CAST(DATEADD(second, HT.ElapsedTime, H.TRDateTime) AS DateTime) AS [Transmission End Date]
, HT.[ElapsedTime] AS [Time taken to send]
, HT.GoodPageCount AS Pages
, HT.[ChannelUsed]
FROM [dbo].History AS H (NOLOCK)
LEFT OUTER JOIN [dbo].HistoryTRX AS HT (NOLOCK) ON H.handle = HT.handle
)
SELECT
Calculate_Date AS [Full Calculated Date]
, CAST(Calculate_Date AS DATE) AS Calculated_Date
, CAST(DATEPART(YYYY , dhm.Calculate_Date) AS VARCHAR ) + '-' + RIGHT('0' + CAST(DATEPART(Month , dhm.Calculate_Date) AS VARCHAR) , 2) AS [Calculated Year-Month]
, CAST(DATEPART(YYYY , dhm.Calculate_Date) AS VARCHAR ) + '-' + RIGHT('0' + CAST(DATEPART(Week , dhm.Calculate_Date) AS VARCHAR) , 2) AS [Calculated Year-Week]
, CAST(DATEPART(YYYY , dhm.Calculate_Date) AS VARCHAR ) + '-' + RIGHT('0' + CAST(DATEPART(DAY , dhm.Calculate_Date) AS VARCHAR) , 2) AS [Calculated Year-Day]
, DATEPART(YYYY, dhm.Calculate_Date) AS [Calculated Year]
, RIGHT('0' + CAST(DATEPART(MM, dhm.Calculate_Date) AS VARCHAR) ,2) AS [Calculated Month]
, DATEPART(Week, dhm.Calculate_Date) AS [Calculated Week]
, DATEPART(DAY, dhm.Calculate_Date) AS [Calculated Day]
, RF.Transmission_ID
, RF.[Transmission Start Date]
, RF.[Transmission End Date]
, RIGHT('0' + CAST(DATEPART(HOUR , RF.[Transmission Start Date]) AS VARCHAR) ,2) + ':' + RIGHT('0' + CAST(DATEPART(Minute , RF.[Transmission Start Date]) AS VARCHAR) ,2) AS [Transmission Start Time]
, RIGHT('0' + CAST(DATEPART(HOUR , RF.[Transmission End Date]) AS VARCHAR) ,2) + ':' + RIGHT('0' + CAST(DATEPART(Minute , RF.[Transmission End Date]) AS VARCHAR) ,2) AS [Transmission End Time]
, RF.[Time taken to send]
, RF.Pages
, RF.[ChannelUsed]
FROM CTE_Text RF
INNER JOIN CTE_DayHourMinutes dhm ON
-- Join where the calculate_date is between the start and end date of the transmission date.
dhm.Calculate_Date >= RF.[Transmission Start Date]
AND
dhm.Calculate_Date <= RF.[Transmission End Date]
I would suggest these changes below based on the code you put above and some guesses on what is missing such as data type and table model, existing index or pk, etc. Update/Info would be nice.
I supposed that data type are as follow
create table History(
ObjectGuid uniqueidentifier
TRDateTime datetime
handle bigint
HistoryTRX
ElapsedTime int
GoodPageCount int
ChannelUsed int
handle bigint
Altough it won't improve the whole query, CTE_DayHourMinutes is faster and shorter this way:
; with CTE_DayHourMinutes(Calculate_Date) as (
select #startDate
union all
select DATEADD(MINUTE, 1, Calculate_Date) from CTE_DayHourMinutes
where Calculate_Date<DATEADD(MINUTE, 60*24-1, #currentDate)
)
Select Calculate_Date From CTE_DayHourMinutes
Option (MaxRecursion 0)
CTE_Text RF table scan
You should first join [dbo].History with CTE_DayHourMinutes as early as possible and try to reduce the scope of this CTE and history table. Right now you are probably scanning the whole History table + all or part of HistoryTRX
LEFT OUTER JOIN [dbo].HistoryTRX
when there is no match between the 2 tables, HT.ElapsedTime is null. Therefore [Transmission End Date] is null and dhm.Calculate_Date >= RF.[Transmission Start Date] AND dhm.Calculate_Date <= RF.[Transmission End Date] do not match. You probably need a inner join and/or need to review/rethink what you want to achieve.
Remove cast and function as much as possible
It looks like most of them are not needed. They also prevent proper usage of the indexes.
Review your indexes
Are they properly set and usefull?

How to remove sql server date time default value

Hi I am pretty new to sql and I keep getting the sql default value 1900-01-01 00:00:00.000. I just want the field to be empty. I thought if I put '' the empty string it would use that instead of the default value. I commented the line where I think the problem is. I have tried other ways like ISNULL and Convert but that does not work. Thanks in advance and if you can explain how the default date works and how to override it that would be much appreciated.
DECLARE #custAccount nvarchar(20)
SET #custAccount='CUS07869'
SELECT 'SM' as [Origin]
,'SN' as [Action Code]
,ST.PurchOrderFormNum as [Order Number]
,SL.ITEMID AS [LINE ITEM]
,SL.QTYORDERED as [Quantity]
,S.SHIPMENTDATE as [Action Date]
,S.TRACKINGNUMBER as [TRACKING]
,ISNULL(S.SHIPMENTDATE, '') as [DATE_SHIPPED]
,S.SHIPMETHOD as [Carrier]
FROM SalesTable ST
INNER JOIN GBP_Shipping S
ON ST.SalesId=S.SalesId AND ST.DataAreaId=S.DataAreaId
INNER JOIN SalesLine SL
ON ST.SalesId=SL.SalesId AND ST.DataAreaId=SL.DataAreaId
WHERE ST.CUSTACCOUNT=#custAccount
AND S.SHIPMENTDATE = convert(varchar, getdate(), 111)
AND ST.salestype!=4
UNION
SELECT 'SM' as [Origin]
,'AN' as [Action Code]
,ST.PurchOrderFormNum as [Order Number]
,SL.ITEMID AS [LINE ITEM]
,SL.QTYORDERED as [Quantity]
,replace(convert(varchar, getdate(), 111), '/', '') as [Action Date]
,'' as [TRACKING]
,'' as [DATE_SHIPPED] --I think this is the problem
,'' as [Carrier]
FROM SalesTable ST
INNER JOIN SalesLine SL
ON ST.SalesId=SL.SalesId AND ST.DataAreaId=SL.DataAreaId
WHERE ST.CUSTACCOUNT=#custAccount
AND ST.CREATEDDATE = convert(varchar, getdate(), 111)
In the first part of your union sets the type of the data in the column.
try
,case when S.SHIPMENTDATE is null then ''
else Convert(VarChar(10),S.SHIPMENTDATE)
end as DATE_SHIPPED
instead
of
,ISNULL(S.SHIPMENTDATE, '') as [DATE_SHIPPED]
SQL does not have an "empty" default date -- you have to set something there. Under the hood they are stored as a binary value, and a binary value of 0 gets transalted to something; here, I'd guess you are using smalldatetime, and I'm reasonably sure 0 = Jan 1, 1900. (Datetime of 0 gets you something in 1753, when the Gregorian calendar officialy started. I'm not sure what coin they flipped for the date/time datatypes new to SQL 2008.)
If you want "no date", you'll probably have to use NULL values, and check for them wherever relevant with the isnull function. Irritating, perhaps, but IMHO it's one of the most legit uses of NULL values in SQL.