How to return second value or column if first one is NULL or is blank:
SELECT IFNULL(NULLIF(col1,''),col2)
The inner NULLIF returns a NULL if col1 is blank. The outer IFNULL returns col1 if it's not blank or NULL and col2 otherwise.
UPDATE table1
SET col1 = t2.col1, col2 = t2.col2
FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id
UPDATE table1 t1 JOIN table2 t2 ON t1.id = t2.id
SET t1.col1 = t2.col2, t1.col2 = t2.col2
ALTER TABLE table-name ADDShort and beautiful. DEFAULT specifies a default value and WITH VALUES instructs SQL Server to populate all rows with the default value.
column-name column-type NOT NULL DEFAULT default-value WITH VALUES
SELECT t.id, trade_date, ...,CASE is a very useful statement in SQL. It can be used either as CASE expression WHEN or CASE WHEN expression. Here, I'm using the later form.
CASE WHEN
(
DATEDIFF(n,GETDATE(),CONVERT(CHAR(10),trade_date,110) + ' ' + cutoff_p) <= 30 AND d.amount_p > 0
AND email_date IS NULL
)
OR
(
DATEDIFF(n,GETDATE(),CONVERT(CHAR(10),trade_date,110) + ' ' + cutoff_r) <= 30 AND d.amount_r > 0
AND email_date IS NULL
)
THEN 1 ELSE 0 END AS alert
FROM ticket t JOIN ticket_detail d ON t.id = d.ticketid
LEFT OUTER JOIN fund f ON d.fundcode = f.fundcode
ORDER BY trade_date, account_name
CONVERT(CHAR(10),trade_date,110) + ' ' + cutoff_pThe trading date is converted into USA standard, or mm-dd-yyyy, a CHAR 10 characters long. Then the cutoff time, which is in the h:mm(A/PM) form, is concatenated at the end. Notice the space in the middle. Without it, the hour will immediately follow year and confuse SQL Server.
THEN 1 ELSE 0 END AS alertstates that if the expression is true, then return 1, else, return 0 and name the column alert.