I've changed this query numerous times but still see '0 rows affected. Everything works in SELECT statement but fails in the UPDATE.
Here is the query:
UPDATE tblVisitLog
SET tblVisitLog.TimeOUT = (SELECT CAST(SUBSTRING(tblScheduleData.E_Time, 1,2 ) + ':' + SUBSTRING(tblScheduleData.E_Time, 3,2) + ':00.000' AS datetime)
FROM tblScheduleData
WHERE tblVisitLog.Encounter_code = tblScheduleData.Encounter_code),
tblVisitLog.Provider = (SELECT Provider
FROM tblScheduleData s
WHERE tblVisitLog.Encounter_code = s.Encounter_code),
tblVisitLog.recStatus = 0,
tblVisitLog.Printed = N'N'
WHERE
tblVisitLog.TimeOUT IS NULL
AND tblVisitLog.Provider IS NULL
The datatypes are:
Encounter_code (int, null)
TimeOUT (datetime, null)
Provider (nvarchar(50), null)
recStatus (smallint, not null)
Printed (nvarchar(50), null)
The values that I'm updating are all NULL, the values I'm pulling in from tblScheduleData.E_Time are varchar(4), null and formatted like '1045'.
Your update statement would be a LOT cleaner using a join here. Something like this.
UPDATE vl
SET TimeOUT = CAST(SUBSTRING(s.E_Time, 1,2 )+ ':' + SUBSTRING(s.E_Time, 3,2) + ':00.000' AS datetime)
, Provider = s.Provider
, recStatus = 0
, Printed = N'N'
from tblVisitLog vl
join tblScheduleData s on vl.Encounter_code = s.Encounter_code
WHERE vl.TimeOUT Is NULL
AND vl.Provider Is Null
The message it's pretty clear '0 rows affected'
So try do this query and you will see an empty result
select * from tblVisitLog
WHERE TimeOUT Is NULL AND Provider Is Null
First change the criteria
Related
ALTER PROCEDURE [dbo].[USP-Search-DocumentNumber]
#DocumentNumber varchar(100) = NULL,
#Company_ID varchar(10) = NULL
AS
BEGIN
SET #Company_ID= (REPLACE (#Company_ID, '''', ''))
SELECT SalesID, DocumentNumber AS 'DocumentNumber', CompanyID
FROM Sales
WHERE (DocumentNumber LIKE '%' + #DocumentNumber+ '%'
OR #DocumentNumber IS NULL)
AND DocumentNumber IS NOT NULL
AND ISNULL(Active, 0) = 1
AND ISNULL(IsCommited, 0) = 0
AND ISNULL(IsCancelled, 0) = 0
AND CAST(CompanyID AS varchar(10)) IN (#Company_ID)
END
From the VB.NET code, I am passing
l_objcmd.CommandText = "USP-Search-DocumentNumber"
l_objcmd.CommandType = CommandType.StoredProcedure
'l_objParam = l_objcmd.Parameters.Add("#SalesID", SqlDbType.VarChar)
'l_objParam.Value = IIf(ViewState("SalesID") = "", Nothing, ViewState("SalesID"))
'l_objParam.Direction = ParameterDirection.Input
l_objParam = l_objcmd.Parameters.Add("#DocumentNumber", SqlDbType.VarChar)
l_objParam.Value = IIf(ViewState("DocumentNumber") = "", Nothing, ViewState("DocumentNumber"))
l_objParam.Direction = ParameterDirection.Input
l_objParam = l_objcmd.Parameters.Add("#Company_ID", SqlDbType.VarChar)
l_objParam.Value = IIf(Session("DocumentNumberForm_CompanyID") = "", Nothing, Session("DocumentNumberForm_CompanyID"))
l_objParam.Direction = ParameterDirection.Input
l_ObjDs = v_ObjBREngine.ExecuteProcedure(l_objcmd)
If Not IsNothing(l_ObjDs) And l_ObjDs.Tables(0).Rows.Count > 0 Then
gvFilterData.DataSource = l_ObjDs.Tables(0).DefaultView
gvFilterData.DataBind()
gvFilterData.Columns(0).Visible = True
Else
l_ObjDs.Tables(0).Rows.Add(l_ObjDs.Tables(0).NewRow())
gvFilterData.DataSource = l_ObjDs
gvFilterData.DataBind()
gvFilterData.Columns(0).Visible = False
End If
The #Company_ID is passing as "1,2,3" but doesn't return result but when I put directly this in where it works.
I have tried multiple things with it but doesn't work. Why ? I have even used the IN operator but still issue.
This code most likely does not do what you want:
CAST(CompanyID AS varchar(10)) IN (#Company_ID)
It is exactly equivalent to:
CAST(CompanyID AS varchar(10)) = #Company_ID
So if #Comapny_ID contains '1,2,3', then it only matches another string this exactly the same.
I get the idea that Company_Id contains a list of ids that are presumably comma separated values. If so, you need to do the comparison in some other way. A common method would be:
CAST(CompanyID AS varchar(10)) IN (SELECT s.value FROM string_split(#Company_Id, ',') s)
In older versions, one method is:
CONCAT(',', CompanyID, ',') LIKE CONCAT('%,', #Company_Id, ',%')
There may be other ways to pass a list in as well. This is intended to address what I think the issue is in your code.
I came across this stored procedure today and I'm confused with the syntax on it. It is doing an UPDATE and the query looks like this:
DECLARE #TransactionStatus tinyint = 1,
#RedeemedAmount decimal(18,2) = 0,
#PromotionCodeAmount decimal(18,2) = 0,
#EventDetailId int = 0
UPDATE PED
SET #RedeemedAmount = PED.RedeemedAmount = PED.RedeemedAmount + PE.PromoCodeAmount,
#PromotionCodeAmount = PE.PromoCodeAmount,
#EventDetailId = PED.Id
FROM dbo.PromotionEvents AS PE
JOIN dbo.PromotionEventDetails AS PED ON PED.EventId = PE.Id
WHERE PED.Id IN (
SELECT TOP 1 PED.ID
FROM dbo.PromotionEvents AS PE
JOIN dbo.PromotionEventDetails AS PED ON PED.EventId = PE.Id
WHERE PE.Id = #EventId
AND PED.Amount >= PED.RedeemedAmount + PE.PromoCodeAmount
AND PE.StartDate <= GETDATE() AND PE.EndDate > GETDATE()
AND PE.MStatusId = 1
AND PED.MStatusId = 1
ORDER BY PED.CreatedDateTime)
This is only a portion of the whole stored procedure. I just need to understand what this part does?
SET #RedeemedAmount = PED.RedeemedAmount = PED.RedeemedAmount + PE.PromoCodeAmount,
Notice that there are two equals signs on that line.
That line does two things at once:
Updates the PromotionEventDetails.RedeemedAmount column
Stores the same value in #RedeemedAmount variable
This seems to be a mix of usual UPDATE ... SET column = expression with SQL Server's "set variable" syntax of SET #variable = expression. Tests show it is impossible to do #a = #b = col1 or col1 = col2 = col3, it only works for one variable and one target column.
Got a problem while importing CSV into a SQL Server database.
I have , , and ,, values in the CSV, so when I compare the values in SQL
b.test = a.test (i.e. '' = ' ') is false. So the insert is done, but test has an unique constraint and I get a constraint validation when b.test = '' and a.test = ' '.
How can I solve this problem?
Here the statement (b.marke = a.marke is the problem):
INSERT INTO wt_umcodierung_bez(prnummer, marke, spk, bez, quelle)
SELECT a.prnummer, a.marke, a.spk, a.bez, a.quelle
FROM trans_wt_umcodierung_bez a
WHERE NOT EXISTS (SELECT 1
FROM wt_umcodierung_bez b
WHERE b.prnummer = a.prnummer
AND b.marke = a.marke
AND b.spk = a.spk)
AND a.spk IN (SELECT spk FROM wt_spk)
You might want to double trim the fields in this case, to make sure you strip off any leading or trailing spaces. If you run into problems with NULL values, you can further wrap a.marke and b.marke in ISNULL, and then LTRIM(RTRIM())
INSERT INTO wt_umcodierung_bez(prnummer, marke, spk, bez, quelle)
SELECT a.prnummer, a.marke, a.spk, a.bez, a.quelle
FROM trans_wt_umcodierung_bez a
WHERE NOT EXISTS (SELECT 1
FROM wt_umcodierung_bez b
WHERE b.prnummer = a.prnummer
AND LTRIM(RTRIM(b.marke)) = LTRIM(RTRIM(a.marke))
AND b.spk = a.spk)
AND a.spk IN (SELECT spk FROM wt_spk)
Query which should be stored as variable in "Execute SQL Task":
Use [Reporting]
Go
DECLARE
#current_month DATETIME,
#current_year DATETIME,
#current_year_final AS INT,
#previous_period_final VARCHAR(2),
#test_period AS VARCHAR (2),
#previous_period_final_2 VARCHAR(2)
SET #current_month = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0)
SET #current_year = DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE()),0)
SET #current_year_final = CASE WHEN LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) = '01' THEN LEFT(CONVERT(VARCHAR,#current_year,112),4)-1 ELSE LEFT(CONVERT(VARCHAR,#current_year,112),4) END
SET #previous_period_final = CASE
WHEN CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) AS INT) - 1 BETWEEN 10 AND 11 THEN CAST(CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) AS INT) - 1 AS VARCHAR) -- Type Varchar
WHEN CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),3),1) AS INT) - 1 BETWEEN 1 AND 8 THEN '0' + CAST(CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),3),1) AS INT) - 1 AS VARCHAR)
WHEN CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) AS INT) - 1 = 9 THEN '09'
WHEN LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) = '01' THEN '12'
ELSE 'Invalid formula' END
SET #previous_period_final_2 = CAST(LEFT(RIGHT(CONVERT(VARCHAR, GETDATE(),112),4),2) AS INT) - 1
-- ### Returns:
-- 1 = 'identical' = row numbers match
-- 0 = 'mis-matched' = row numbers do not match
select sum(rows_identical) as rows from
(
select CAST(CAST(case when count_rows_raw = count_rows_facts then 1 else 0 end as bit)as int) as rows_identical
--,SQL_VARIANT_PROPERTY(CAST(CAST(case when count_rows_raw = count_rows_facts then 1 else 0 end as bit)as int),'BaseType') -- ### EXCELLENT WAY TO RETRIEVE DATATYPE ###
from
(
select
(
select SUM(#rows_facts) as #rows_facts from
(
select COUNT(ID) as #rows_facts, 'finalized_entries_facts_table' as type from facts_reporting
where YearMonthID in (select YearMonthID from dim_year_month as yyMM
where yyMM.YearMonth = CAST(#current_year_final AS Varchar)+'_'+CAST(#previous_period_final AS Varchar))
and SourceID IN (select SourceID from dbo.dim_source where Source = 'Unlocks')
union
select COUNT(ID) as #rows_facts, 'missing_entries_facts_table' as type from missing_ids_Unlocks_raw
where YearMonthID in (select YearMonthID from dim_year_month as yyMM
where yyMM.YearMonth = CAST(#current_year_final AS Varchar)+'_'+CAST(#previous_period_final AS Varchar))
and SourceID IN (select SourceID from dbo.dim_source where Source = 'Unlocks')
) as rows
) as count_rows_facts,
(
SELECT count(*)as #rows_raw from UnlocksRawCSV_table as raw
Where Year_Month_inserted = CAST(#current_year_final AS Varchar) + '_' + #previous_period_final
) as count_rows_raw
)
as row_checks
)
as count_check
--where rows_identical <> 0
Variable definition and Result Set mapping in SSIS:
In the Execute SQL Task I have selected "Result Set = Single row". I have also tried "None". I have put a post-execute Breakpoint on the Execute SQL Task and get this:
== Why am I getting a 0 as value in SSIS while I am getting a 1 if I execute this query (see above) in SQL Server directly?
The precedence constraint in the subsequent task look like this:
EDIT 1: Changing this expression to #RowCheck == 0 does not change anything as the task still fails on execution with the same error:
Error: No result rowset is associated with the execution of this query
EDIT: 2: Changing the Value in the Precedence Constraint Editor from "Success" to "Failure" works but I don't understand why the task itself fails and why it generates the above mentioned error message? However, despite proceeding with the package the value displayed for variable RowCheck does not make any sense as it is always zero, regardless of that the Query returns...
EDIT 3: Screen of General Tab for Execute SQL Statement (I have also tried with "Single Row" and above mentioned Result Set Mapping:
I am trying to build an SQL SP to do a query for report. It has several arguments that could be NULL or should have a value. I am using the code below. Is there another alternative way of doing this, more cleanly or more proper. I am assuming that if an Argument is Null, i would just do a 1=1 filter condition.
DECLARE #Arg1 VARCHAR(10) = NULL,
#Arg2 VARCHAR(10) = NULL
SELECT * FROM Table1
WHERE
(CASE WHEN (#Arg1 IS NULL) THEN
1
ELSE
#Arg1
END) =
(CASE WHEN (#Arg1 IS NULL) THEN
1
ELSE
Location
END)
AND
(CASE WHEN (#Arg2 IS NULL) THEN
1
ELSE
#Arg2
END) =
(CASE WHEN (#Arg2 IS NULL) THEN
1
ELSE
Sex
END)
Can't you just do it like this?
where
(#Arg1 is null or #Arg1 = Location)
and
(#Arg2 is null or #Arg2 = Sex)
Then if #Arg1 (or 2) is null then that part of the predicate is TRUE and and'd with the next predicate.
Another possibility, even shorter, is to use Coalesce():
where COALESCE(#Arg1, Location) = Location
and COALESCE(#Arg2, Sex) = Sex
That is, when #arg1 and #arg2 have values, use them, otherwise, otherwise use the column in question; since Location = Location is always true (at least when not NULL, same issue in your own code).
Another possibility is
where IsNull(#Arg1,Location) = Location
and IsNull(#Arg2, Sex) = Sex
This is pretty much the #IFLoop answer, but IsNull is slightly faster than COALESCE.
Which is quicker COALESCE OR ISNULL?
Running the the following queries (in my machine):
DECLARE #ARG1 VARCHAR(50) = 'xserver_name'
select *
from sys.tables
where IsNull(#Arg1, name) = name
Cost: 27%
select *
from sys.tables
where Coalesce(#Arg1,name) = name
Cost 27%
select *
from sys.tables
where (#Arg1 is null or #Arg1 = name)
Cost 45%
Run and see the Execution plan please
But if the number of rows of the table increases, the difference disapear, because is is dominated by the table scan time:
select *
from sys.all_Columns
where IsNull(#Arg1, name) = name
Cost: 33%
select *
from sys.all_Columns
where Coalesce(#Arg1,name) = name
Cost 34%
select *
from sys.all_Columns
where (#Arg1 is null or #Arg1 = name)
Cost 33%