sql server update + output returning empty value - sql-server

everybody.. I'm a newbie and I'm trying to make my first "little more complicated query" but does not work fully: here it is:
if NOT EXISTS (Select id,selector from Messages where MID='SYCKY')
Insert into Messages (MID,selector) Values ('SYCKY', 'SaraB|')
ELSE
if exists (
select '1'
from Messages
where charindex ('SaraB|',selector)>0
)
Update Messages
set selector = replace(selector,'SaraB|','') output inserted.selector
where MID='SYCKY'
ELSE
Update Messages
set selector = selector+'SaraB|' output inserted.selector
where MID='SYCKY'
it performs the action required, but in the output I have an empty field only
tried also to add an extra field, like this:
if NOT EXISTS (Select id,selector from Messages where MID='SYCKY')
Insert into Messages (MID,selector) Values ('SYCKY', 'SaraB|')
ELSE
if exists (select '1' from Messages where charindex ('SaraB|',selector)>0)
Update Messages
set selector = replace(selector,'SaraB|',''), T='1' output inserted.T
where MID='SYCKY'
ELSE
Update Messages
set selector = selector+'SaraB|', T='0' output inserted.T
where MID='SYCKY'
but result is the same: T is empty, while I need to to know if "SaraB|" has been added or deleted from the field
What's wrong?

Not quite sure... but maybe this is what you want?
if NOT EXISTS (Select id,selector from Messages where MID='SYCKY')
Insert into Messages (MID,selector) Values ('SYCKY', 'SaraB|')
ELSE
if exists (
select '1'
from Messages
where charindex ('SaraB|',selector)>0
)
BEGIN
Update Messages
set selector = replace(selector,'SaraB|','') output inserted.selector
where MID='SYCKY';
SELECT 'If was true';
END
ELSE
BEGIN
Update Messages
set selector = selector+'SaraB|' output inserted.selector
where MID='SYCKY';
SELECT 'If was false';
END
This will "return" different values depending on how the if evaluates.

Related

What is wrong with my UPDATE statement WHERE NOT EXISTS?

What I am trying to accomplish is to update the ISCURRENT field to 'N' and the EFFECTIVE_END_DATE field to the current date if the record of its type does not have the most recent EFFECTIVE_START_DATE.
An error does not get thrown it just tells me "0 rows affected" but I created a record with a more recent EFFECTIVE_START_DATE which should affect the other record in the table that has the earlier EFFECTIVE_START_DATE.
Here is an image of the 2 records I'm using to test it out.
The record that has a KTEXT of '400 Atlantic' should be changed from this script to have an ISCURRENT ='N' and EFFECTIVE_END_DATE=GETDATE() because the record with the KTEXT of 500 Maria has a more recent EFFECTIVE_START_DATE
UPDATE [SAP].[src_gl_sap_m_cepct]
set ISCURRENT='N',
EFFECTIVE_END_DATE=GETDATE()
WHERE NOT EXISTS (SELECT [SPRAS],
[PRCTR],
MAX(EFFECTIVE_START_DATE)
FROM [SAP].[src_gl_sap_m_cepct] AS A
WHERE CONCAT([SAP].[src_gl_sap_m_cepct].[SPRAS],[SAP].[src_gl_sap_m_cepct].[PRCTR]) = CONCAT(A.[SPRAS],A.[PRCTR]
)
GROUP BY [SPRAS],[PRCTR]);
Thank you !
Correct me if I am wrong, but this part of your query
FROM [SAP].[src_gl_sap_m_cepct] AS A
WHERE CONCAT([SAP].[src_gl_sap_m_cepct].[SPRAS],[SAP].[src_gl_sap_m_cepct].[PRCTR]) = CONCAT(A.[SPRAS],A.[PRCTR]
can also be written like this (because you have a self join)
FROM [SAP].[src_gl_sap_m_cepct] AS A
WHERE CONCAT(A.[SPRAS], A.[PRCTR]) = CONCAT(A.[SPRAS], A.[PRCTR]
And like this I notice that you are simply comparing a value to the same value again.
Thus this will always evaluate as TRUE
And thus the not exists clause will never evaluate as true
And therefore no updates will happen.
I think something like this might work for you
UPDATE c
set c.ISCURRENT='N',
c.EFFECTIVE_END_DATE = GETDATE()
FROM SAP.src_gl_sap_m_cepct c
WHERE EXISTS ( select 1
FROM SAP.src_gl_sap_m_cepct AS A
WHERE CONCAT(c.SPRAS, c.PRCTR) = CONCAT(A.SPRAS, A.PRCTR)
AND A.EFFECTIVE_START_DATE > c.EFFECTIVE_START_DATE
)
If I understood correctly, the statement should be like this:
UPDATE c
set ISCURRENT='N',
EFFECTIVE_END_DATE = GETDATE()
FROM [SAP].[src_gl_sap_m_cepct] c
WHERE EXISTS (
SELECT 1
FROM [SAP].[src_gl_sap_m_cepct] AS A
WHERE CONCAT(c.[SPRAS], c.[PRCTR]) = CONCAT(A.[SPRAS],A.[PRCTR])
AND c.EFFECTIVE_START_DATE < A.EFFECTIVE_START_DATE
);

Update multiple tables with one query

Record to update
select *
from Event_Measurable em
join Observation_Measurable om on em.Event_GUID = om.Event_GUID
where observation_guid in (8786975, 285886, 85976, 786976)
Update these records as follows:
set observation_value_text = '.',
observation_value_numeric = NULL,
om.status = 'D',
em.status = 'D',
I need help to update and set this values from the results of the query above. Can any help me. I have tried to update the table but it failed.
Try this:
update X set
observation_value_text = '.'
, observation_value_numeric = NULL
, om.status = 'D'
, em.status = 'D'
from
(
select
*
from Event_Measurable em
join Observation_Measurable om on em.Event_GUID = om.Event_GUID
where observation_guid in (8786975, 285886, 85976, 786976)
) X
Let me know if it works?
Your set list references multiple tables: that is invalid as only one table can be updated with one statement. You need to run 2 update statements so you either repeat the join in the second update or first put the result in a temp table and join that to the actual to-be-updated table. You might want to put the whole thing to a transaction to be able to roll back on error. See this reference.

What code is needed to conditionally provide a value to a field in a beforeinsert trigger?

I need to store a string value in a field in a table, specifically in its Subcategory VarChar(50) column.
The value of Subcategory prior to this post processing is either 0 or 1; I need to change that to a more human-friendly value.
I haven't created a database trigger in decades and need some help with the code. This is my pseudo SQL (a hodgepodge of SQL and VB):
CREATE OR REPLACE TRIGGER tr_CustomerCategoryLog_BeforeInsert
BEFORE INSERT ON CustomerCategoryLog FOR EACH ROW
DECLARE _Category = :new.Category;
DECLARE _Subcategory = :new.Subcategory;
BEGIN
If _Category = "New"
If _Subcategory = 0
:new.Subcategory := 'New';
End If
Else If _Subcategory = 1
:new.Subcategory := 'Assumed';
End If
End If
If _Category = "Existing"
If _Subcategory = 0
:new.Subcategory := 'Existing';
End If
Else If _Subcategory = 1
:new.Subcategory := 'Organic'
End If
End If
Return "Unknown"
End Function
END;
If the logic isn't clear, in semi-plain English it is:
If the value of the Category field is "New", set the Subcategory field value also to "New" if the value of Subcategory is currently 0; otherwise, set it to "Assumed"
If the value of the Category field is "Existing", set the Subcategory field value also to "Existing" if the value of Subcategory is currently 0; otherwise, set it to "Organic"
Maybe I need to give Steely Dan's album "Trigger Logic" a listen.
UPDATE
I think the answer will work, but it's not complete enough for me.
Since I apparently have Oracle code mixed up in the pseudoSQL above, what would the complete code need to look like (to create a BeforeInsert trigger on the CustomerCategoryLog table)?
Is this more like it:
CREATE TRIGGER tr_CustomerCategoryLog_BeforeInsert
ON CustomerCategoryLog
INSTEAD OF INSERT
AS
BEGIN
SELECT
CASE
WHEN #Category = 'New'
THEN CHOOSE(#Subcategory + 1, 'New', 'Assumed')
WHEN #Category = 'Existing'
THEN CHOOSE(#Subcategory + 1, 'Existing', 'Organic')
ELSE 'Unknown'
END
END
?
I tend to avoid triggers (perhaps a character flaw... I also don't like mashed potatoes), but the following illustration could simplify your logic
Declare #Category varchar(50) = 'Existing'
Declare #Subcategory int = 1 -- works if BIT
Select case when #Category = 'New' then choose(#Subcategory+1,'New','Assumed')
when #Category = 'Existing' then choose(#Subcategory+1,'Existing','Organic')
else 'Unknown' end
Returns
Organic

Insert not working using MERGE in SQL server

I have a stored proc with the below query to insert/update using a MERGE in SQL Server but the query works fine for update, but its not working for Insert.
Although I gets correct updated records in Target but for new inserts, it fails.
Basically, i have 4 tables.SUPPORT_STAFF_BAK is the target table which needs to be updated from source table UNIQUE_DUP_TEST based on few conditions from other two tables(REF_FUNCTION,DATA_PERIOD) which i tried to fulfill using joins.
Based on the conditions, we need to check in target, if the same ggid exists for current data_period we need to update it else we need to insert new record again, based on the condition.
MERGE SUPPORT_STAFF_BAK AS SUPP_STAFF
USING
(SELECT G_UNIQUE.[GLOBAL_ID],
G_UNIQUE.[FIRST_NAME],
G_UNIQUE.[LAST_NAME],
G_UNIQUE.[EMAIL],
G_UNIQUE.[Gender],
G_UNIQUE.[DATE_OF_BIRTH],
G_UNIQUE.[PRODUCTION_UNIT_CODE],
ORG.[LEGAL_ENTITY_COUNTRY_CODE],
ORG.[LEGAL_ENTITY_COUNTRY],
G_UNIQUE.[JOB_NAME],
ORG.[BU_CODE],
ORG.[BU_NAME],
ORG.[SBU_CODE],
ORG.[SBU_NAME],
G_UNIQUE.[GRADE_LETTER],
CASE
WHEN G_UNIQUE.[EMPLOYEE_STATUS] = 'A' THEN 'Active'
WHEN G_UNIQUE.[EMPLOYEE_STATUS] = 'S' THEN 'Suspended'
WHEN G_UNIQUE.[EMPLOYEE_STATUS]= 'T' THEN 'Terminated'
END AS [EMPLOYEE_STATUS],
CASE WHEN G_UNIQUE.[CATEGORY] = 'DSS' THEN G_UNIQUE.[CATEGORY_DETAIL] ELSE ''
END AS [CATEGORY],
G_UNIQUE.[CATEGORY_DETAIL],
G_UNIQUE.[FIRST_JOINING_DATE],
PERIOD.DATA_PERIOD_ID
FROM UNIQUE_DUP_TEST G_UNIQUE
INNER JOIN GDH_ORG ORG
ON G_UNIQUE.PRODUCTION_UNIT_CODE=ORG.PRODUCTION_UNIT_CODE
INNER JOIN REF_FUNCTION FUNC
ON G_UNIQUE.CATEGORY_DETAIL=FUNC.FUNCTION_CODE
INNER JOIN DATA_PERIOD PERIOD
ON FUNC.FUNCTION_ID=PERIOD.FUNCTION_ID
WHERE PERIOD.DATA_YEAR=YEAR(GETDATE()) AND PERIOD.DATA_MONTH=MONTH(GETDATE())
) AS G_SOURCE
ON SUPP_STAFF.GGID = G_SOURCE.GLOBAL_ID AND SUPP_STAFF.PRODUCTION_UNIT_CODE=G_SOURCE.PRODUCTION_UNIT_CODE
AND SUPP_STAFF.DATA_PERIOD_ID=G_SOURCE.DATA_PERIOD_ID
WHEN MATCHED THEN
UPDATE SET
[SUPP_STAFF].[FIRST_NAME] = G_SOURCE.[FIRST_NAME],
[SUPP_STAFF].[LAST_NAME] = G_SOURCE.[LAST_NAME],
[SUPP_STAFF].[EMAIL] = G_SOURCE.[EMAIL],
[SUPP_STAFF].[GENDER] = G_SOURCE.[Gender],
[SUPP_STAFF].[DATE_OF_BIRTH] = G_SOURCE.[DATE_OF_BIRTH],
[SUPP_STAFF].[LEGAL_ENTITY_COUNTRY_CODE] = G_SOURCE.[LEGAL_ENTITY_COUNTRY_CODE],
[SUPP_STAFF].[LEGAL_ENTITY_COUNTRY_NAME] = G_SOURCE.[LEGAL_ENTITY_COUNTRY],
[SUPP_STAFF].[GCM_ROLE] = G_SOURCE.[JOB_NAME],
[SUPP_STAFF].[BU_CODE] = G_SOURCE.[BU_CODE],
[SUPP_STAFF].[BU_NAME] = G_SOURCE.[BU_NAME],
[SUPP_STAFF].[SBU_CODE] = G_SOURCE.[SBU_CODE],
[SUPP_STAFF].[SBU_NAME] = G_SOURCE.[SBU_NAME],
[SUPP_STAFF].[GRADE] = G_SOURCE.[GRADE_LETTER],
[SUPP_STAFF].[EMPLOYEE_STATUS] = G_SOURCE.[EMPLOYEE_STATUS],
[SUPP_STAFF].[EMPLOYEE_CATEGORY] = G_SOURCE.[CATEGORY],
[SUPP_STAFF].[START_DATE] = G_SOURCE.[FIRST_JOINING_DATE],
[SUPP_STAFF].[UPDATE_DATE] = GETDATE(),
[SUPP_STAFF].[UPDATE_USER] = CASE WHEN G_SOURCE.[EMPLOYEE_STATUS]='Terminated' THEN 'Delete'
WHEN G_SOURCE.[EMPLOYEE_STATUS]<>'Terminated' THEN 'Update'
END,
[SUPP_STAFF].[SUPPORT_STAFF_FUNCTION] = CASE WHEN G_SOURCE.[EMPLOYEE_STATUS]='Terminated' THEN NULL
WHEN G_SOURCE.[EMPLOYEE_STATUS]<>'Terminated' THEN G_SOURCE.[CATEGORY_DETAIL]
END
WHEN NOT MATCHED AND G_SOURCE.[CATEGORY] = 'CC1'
AND G_SOURCE.[EMPLOYEE_STATUS] IN ('A, S')
THEN
INSERT( [GGID],
[FIRST_NAME],
[LAST_NAME],
[EMAIL],
[GENDER],
[DATE_OF_BIRTH],
[LEGAL_ENTITY_COUNTRY_CODE],
[LEGAL_ENTITY_COUNTRY_NAME],
[GCM_ROLE],
[BU_CODE],
[BU_NAME],
[SBU_CODE],
[SBU_NAME],
[GRADE],
[EMPLOYEE_STATUS],
[EMPLOYEE_CATEGORY],
[START_DATE],
[UPDATE_DATE],
[UPDATE_USER],
[SUPPORT_STAFF_FUNCTION]
)
VALUES (
G_SOURCE.[GLOBAL_ID],
G_SOURCE.[FIRST_NAME],
G_SOURCE.[LAST_NAME],
G_SOURCE.[EMAIL],
G_SOURCE.[Gender],
G_SOURCE.[DATE_OF_BIRTH],
G_SOURCE.[LEGAL_ENTITY_COUNTRY_CODE],
G_SOURCE.[LEGAL_ENTITY_COUNTRY],
G_SOURCE.[JOB_NAME],
G_SOURCE.[BU_CODE],
G_SOURCE.[BU_NAME],
G_SOURCE.[SBU_CODE],
G_SOURCE.[SBU_NAME],
G_SOURCE.[GRADE_LETTER],
G_SOURCE.[EMPLOYEE_STATUS],
G_SOURCE.[CATEGORY_DETAIL],
G_SOURCE.[FIRST_JOINING_DATE],
GETDATE(),
'Insert',
G_SOURCE.[CATEGORY_DETAIL]
)
OUTPUT $action,
INSERTED.GGID AS GGID;
SELECT ##ROWCOUNT;
One of your assumptions is wrong. Either the source query has less rows than you think, or there is a match, or the insert condition is not met. Otherwise the query is OK.
To debug this I'd insert the source query into a temp table and manually inspect its contents to make sure they are what you expect.
You can then join to the target to see if your inserts maybe are converted to updates (e.g. select * from Source join Target on ...). Internally, a MERGE is just a full outer join anyway and you can reproduce that manually.
Right now nobody can tell you the exact answer. You need to debug this yourself and examine your data.
Finally I found the error. The error was at the below 2 places -
CASE WHEN G_UNIQUE.[CATEGORY] = 'DSS' THEN G_UNIQUE.[CATEGORY_DETAIL] ELSE '' END AS [CATEGORY],
I replaced it with
CASE WHEN G_UNIQUE.[CATEGORY] = 'DSS' THEN G_UNIQUE.[CATEGORY_DETAIL] ELSE ''
END AS [EMPLOYEE_FUNCTION],
Also I included one more column in my Source query which was missing-
G_UNIQUE.[CATEGORY],
Also, there below wrong code
WHEN NOT MATCHED AND G_SOURCE.[CATEGORY] = 'CC1'
AND G_SOURCE.[EMPLOYEE_STATUS] IN ('A, S')
was replaced by the below correct code-
WHEN NOT MATCHED AND G_SOURCE.[CATEGORY] = 'CC1'
AND G_SOURCE.[EMPLOYEE_STATUS] IN ('Active', 'Suspended')
Actually, I was missing 1 source column and was checking the value for the same while inserting and hence the insert was failing.
Also,in the source for Employee_status i checked the values as A,S and T and then replaced them with Active,Suspended,Terminated but while inserting in the When not matched , i was checking the value for A,S,T which every time was returning false and hence insert failed.

how to add a drop down list

Report needs option to select multiple super product types
Selection of multiple super product types?
IF #superProductType = 'ALL'
INSERT INTO #ProductDetails
SELECT pt_sp_type_c, pt_sb_type_c
FROM product..p_type_p_type
WHERE pt_sp_type_c NOT IN ('EQUITY','OPTEQTY')
AND p_type_use_sp_c= 'RPCDB'
AND p_type_use_sb_c = 'TRD'
AND pt_rel_stat_c = 'ACTIVE'
ELSE
INSERT INTO #ProductDetails
SELECT pt_sp_type_c, pt_sb_type_c
FROM product..p_type_p_type
WHERE pt_sp_type_c NOT IN ('EQUITY','OPTEQTY')
AND pt_sp_type_c IN (#superProductType)
AND p_type_use_sp_c= 'RPCDB'
AND p_type_use_sb_c = 'TRD'
AND pt_rel_stat_c = 'ACTIVE'
I have a parameter here #super product type,can anyone help me how to change this code
Here in this code i need to make some changes: ---parameter is #superProductType
The above code was for the option to select multiple super product types
when i select All and one value from the drop down list like 'ALL','ASKF'
both the above conditions in the code if else will fail
It should not get selected ALL and other ASKF at the same time
either should has to select
How can we differentiate that ALL not selecting ALL from together
if we select ALL remaining values in the drop down list must be deleted
It should not have two values selected together IF ALL only ALL has to select remaining should discard
I am not sure how to eliminate the rest of values in the drop down list
looking for suitable solution,can anybody see the code abnove and tell me what is the change i have to do in the code.
If you have set the SSRS parameter to Multivalue then you should change the query to use IN (#ParamName) syntax. so your query would become:
IF #superProductType = 'ALL'
INSERT INTO #ProductDetails
SELECT pt_sp_type_c, pt_sb_type_c
FROM product..p_type_p_type
WHERE pt_sp_type_c NOT IN ('EQUITY','OPTEQTY')
AND p_type_use_sp_c= 'RPCDB'
AND p_type_use_sb_c = 'TRD'
AND pt_rel_stat_c = 'ACTIVE'
ELSE
INSERT INTO #ProductDetails
SELECT pt_sp_type_c, pt_sb_type_c
FROM product..p_type_p_type
WHERE pt_sp_type_c NOT IN ('EQUITY','OPTEQTY')
AND pt_sp_type_c IN ( #superProductType )
AND p_type_use_sp_c= 'RPCDB'
AND p_type_use_sb_c = 'TRD'
AND pt_rel_stat_c = 'ACTIVE'

Resources