I am a beginner and first time in sql procedure. If the user doesnt give any value to the parameter, it will return all the item. But I am trying to adding more where clause based on user input. I know there is if-else statement in sql procedure, but I have no idea if is it possible to append more condition.
Here is the statement
#FirstName varchar (50)
AS
SELECT distinct [user_identity], [first name],
[last name], email, Name, orderdate,RenewalCount, RenewalDate
FROM
db.[dbo].Users,
db.[dbo].[Order],
db.[dbo].[Subscription],
db.[dbo].[Products],
db.[dbo].[Order_Details]
WHERE
db.[dbo].Users.user_identity = db.[dbo].Subscription.userid AND
db.[dbo].Users.user_identity = db.[dbo].[Order].userid AND
db.[dbo].[Order].Orderid = db.[dbo].[Order_Details].OrderId AND
db.[dbo].Products.ProductId = db.[dbo].[Order_Details].Productid AND
db.[dbo].[Order_Details].OD_Id = db.[dbo].[Subscription].OD_Id
//if #firstname is not null and not empty
//append where clause condition
//AND db.[dbo].Users.[first name] = #FirstName
Thanks in advance!
Your where condition should be like this:
WHERE
db.[dbo].Users.user_identity = db.[dbo].Subscription.userid AND
db.[dbo].Users.user_identity = db.[dbo].[Order].userid AND
db.[dbo].[Order].Orderid = db.[dbo].[Order_Details].OrderId AND
db.[dbo].Products.ProductId = db.[dbo].[Order_Details].Productid AND
db.[dbo].[Order_Details].OD_Id = db.[dbo].[Subscription].OD_Id AND
(#FirstName IS NULL OR #FirstName = '' OR db.[dbo].Users.[first name] = #FirstName)
append below condition in your where condition
where #FirstName=case when isnull(#firstname,'')<>'' then db.[dbo].Users.[first name] else #FirstName end
Related
Code is showing an error
Merge statements with a WHEN NOT MATCHED [BY TARGET] clause must target a hash distributed table
Also please verify that the overall syntax is fine or not?
MERGE IR_CREDITREQUEST_SPTESTING AS T
USING (
SELECT
TT.TaxYear
,TT.TaxPayerSSN
,TT.EngagementID
,TT.CreditRequestType
,TT.BorrowerID
,TT.NameSuffix
,TT.FirstName
,TT.MiddleName
,TT.LastName
,TT.SpouseName
,TT.SpouseSSN
,TT.PrintPositionType
,TT.MaritalStatusType
,TT.StreetAddress
,TT.City
,TT.State
,TT.PostalCode
,TT.Type
,TT.Value
,TT.RequestDateTime
,TT.CreatedDateTime
,TT.RequestProcessed
,TT.BorrowerResidencyType
,TT.isActive
FROM
IR_CREDITREQUEST_SPTESTING TT
INNER JOIN (
select DISTINCT
A.TaxYear,
A.[TaxPayer-SSN] AS TaxPayerSSN,
A.EngagementID AS EngagementID,
CASE
WHEN A.[Filing Status] = 'MFJ' THEN 'Joint'
ELSE A.[Filing Status]
END AS [CreditRequestType],
'' AS BorrowerID ,
A.[TaxPayer-Title/Suffix] AS NameSuffix,
A.[TaxPayer-FirstName] AS FirstName,
'' AS MiddleName,
A.[TaxPayer-LastName] AS LastName,
B.[Spouse-FirstName] + ' ' + B.[Spouse-LastName] AS [SpouseName],
B.[Spouse-SSN] AS [SpouseSSN],
CASE
WHEN A.[Filing Status] = 'MFJ' THEN 'CoBorrower'
WHEN A.[Filing Status] = 'Single' THEN 'Borrower'
ELSE A.[Filing Status]
END AS [PrintPositionType],
CASE
WHEN B.[Spouse-FirstName] IS not null THEN 'Married'
ELSE 'Unmarried'
END AS [MaritalStatusType],
C.[Address] AS StreetAddress,
C.City AS City,
C.[State] AS State,
C.[Postal Code] AS PostalCode,
A.[Primary Contact] AS Type,
A.[TaxPayer-Home/Evening Telephone Number] AS Value,
NULL AS RequestDateTime,
GETDATE() AS CreatedDateTime,
NULL AS RequestProcessed,
NULL AS BorrowerResidencyType,
0 AS IsActive
from DimTaxPayerInfo A
LEFT join DimTaxPayerSpouseInfo B on A.[TaxPayer-SSN] = B.[TaxPayer-SSN] AND B.TaxSoftwareId = 4
LEFT join stg.stg_DimTaxPayerAddress C on A.[TaxPayer-SSN] = C.[TaxPayer-SSN]
WHERE A.[TaxPayer-SSN] != ''
) as Y
ON TT.[EngagementID] = Y.[EngagementID]
) DD
ON T.[EngagementID] = DD.[EngagementID]
WHEN MATCHED THEN
Update
SET T.TaxYear = DD.TaxYear
,T.TaxPayerSSN = dd.TaxPayerSSN
,T.EngagementID = dd.EngagementID
,T.CreditRequestType = dd.CreditRequestType
,T.BorrowerID = dd.BorrowerID
,T.NameSuffix = dd.NameSuffix
,T.FirstName = dd.FirstName
,T.MiddleName = dd.MiddleName
,T.LastName = dd.LastName
,T.SpouseName = dd.SpouseName
,T.SpouseSSN = dd.SpouseSSN
,T.PrintPositionType = dd.PrintPositionType
,T.MaritalStatusType = dd.MaritalStatusType
,T.StreetAddress = dd.StreetAddress
,T.City = dd.City
,T.State = dd.State
,T.PostalCode = dd.PostalCode
,T.Type = dd.Type
,T.Value = dd.Value
,T.RequestDateTime = dd.RequestDateTime
,T.CreatedDateTime = dd.CreatedDateTime
,T.RequestProcessed = dd.RequestProcessed
,T.BorrowerResidencyType = dd.BorrowerResidencyType
,T.IsActive = dd.IsActive
WHEN NOT MATCHED THEN
INSERT
( TaxYear
,TaxPayerSSN
,EngagementID
,CreditRequestType
,BorrowerID
,NameSuffix
,FirstName
,MiddleName
,LastName
,SpouseName
,SpouseSSN
,PrintPositionType
,MaritalStatusType
,StreetAddress
,City
,State
,PostalCode
,Type
,Value
,RequestDateTime
,CreatedDateTime
,RequestProcessed
,BorrowerResidencyType
,IsActive
)
values (
dd.TaxYear
,dd.TaxPayerSSN
,dd.EngagementID
,dd.CreditRequestType
,dd.BorrowerID
,dd.NameSuffix
,dd.FirstName
,dd.MiddleName
,dd.LastName
,dd.SpouseName
,dd.SpouseSSN
,dd.PrintPositionType
,dd.MaritalStatusType
,dd.StreetAddress
,dd.City
,dd.State
,dd.PostalCode
,dd.Type
,dd.Value
,dd.RequestDateTime
,dd.CreatedDateTime
,dd.RequestProcessed
,dd.BorrowerResidencyType
,dd.IsActive
);
Your Merge Statement looks correct. This error is mostly seen in Azure Synapse. Make sure your target table is hash distributed to avoid this error.
Refer to the answer posted in the thread for a similar error.
I am trying to add variable values in WinAutomation into a spreadsheet by column header for every row that doesn't have a value. I've tried two different methods (insert into and update). I am getting the following error: "Runtime Error: Error in SQL Statement: Syntax error in INSERT INTO statement." Does anyone see something that I did wrong here that is causing said error?
INSERT INTO [Sheet1$]
[SAP Employee ID] VALUES(%SapEmployeeNumber%)
WHERE RowNumber IS null
UPDATE [Sheet1$] SET
([SAP Employee ID] = %SapEmployeeNumber%
,[Concur Travel] = %CreditOrOutofPocket%
,[Participant Name] = %ParticipantName%
,[Participant Birth Date] = %ParticipantBirth%
,[Work Location] = %ParticipantWorkLocation%
,[Street Address] = %ParticipantStreetAddress%
,[City] = %ParticipantCity%
,[State] = %ParticipantState%
,[Zip] = %ParticipantZip%
,[Participant Email] = %ParticipantEmail%
,[Contact Phone] = %ParticipantContactPhone%
,[Credit Card Profile] = %ParticipantCreditProfile%
,[Credit Limit] = %ParticipantCreditLimit% )
WHERE
[SAP Employee ID] IS NULL;
I have a stored procedure which will update the album details if a album id is present in the table , if not it will add a new record.
User some times can update all values, or some times leaves some values. So in case if the user leave the values for updating old data should be kept in table.
For this i found solution to make use of coasesce in sql...
I wrote my SP as:
UPDATE [dbo].[tbl_M_Album]
SET [AlbumName] = #AlbumName
,[ImageName] = #Imagename
,[Description] = coalesce(#Description,[Description])
,[Imagepath] = #Imagepath
,[UpdatedBy] = #CreatedBy
,[UpdatedDate] = #CreatedDate
where AlbumID =#AlbumId
end
If i did not send the Description the old data is not keeping, it is overriding by empty data.
Please some one help me if i have any mistakes..
The value of #Description you pass is blank or empty, not NULL.
COALESCE and other null checking functions treat '' as a non null value.
These are all true,
NULL IS NULL
'' IS NOT NULL
' ' IS NOT NULL
If you want to check for NULL, '' (empty) or ' ' (whitespace), you could use
COALESCE(LEN(TRIM(#Description)), 0) = 0
or, for just NULL and empty,
COALESCE(LEN(#Description), 0) = 0
but, it would be more efficient to avoid passing empty or blank values.
You could rewrite your SP like this
IF COALESCE(LEN(TRIM(#Description)), 0) = 0
UPDATE [dbo].[tbl_M_Album]
SET
[AlbumName] = #AlbumName
,[ImageName] = #Imagename
,[Imagepath] = #Imagepath
,[UpdatedBy] = #CreatedBy
,[UpdatedDate] = #CreatedDate
WHERE
[AlbumID] = #AlbumId;
ELSE
UPDATE [dbo].[tbl_M_Album]
SET
[AlbumName] = #AlbumName
,[ImageName] = #Imagename
,[Description] = #Description
,[Imagepath] = #Imagepath
,[UpdatedBy] = #CreatedBy
,[UpdatedDate] = #CreatedDate
WHERE
[AlbumID] = #AlbumID;
Check if the value assigned for #Description is an empty string or NULL. If you pass an empty string in #Description then that is the problem. Only passing NULL will "default" to the next non-null value (this applies to both COALESCE or ISNULL).
Hope this helps.
Use this query.
UPDATE [dbo].[tbl_M_Album]
SET [AlbumName] = #AlbumName
,[ImageName] = #Imagename
,[Description] = Case WHEN (#Description IS NULL OR LTRIM(RTRIM(#Description) = '')
THEN [Description]
ELSE #Description
,[Imagepath] = #Imagepath
,[UpdatedBy] = #CreatedBy
,[UpdatedDate] = #CreatedDate
where AlbumID =#AlbumId
end
Need to write a procedure to retrieve data in which some selection criteria were not taken into procedure if a user not enters a value. I am filtering :
WHERE #ts = [ts] or #username = [username]
or #ip = [ip] or #my_category = [my_category]
or #my_name = [my_name] or #nm1_name = [nm1_name]
or #param = [param] or #short_descr = [short_descr]
When I call a stored procedure and when passed one of the parameters that filtering works, and when I write some ,only one filtering work (because I have in my logic 'or'). Replaced by 'and' not satisfied unnecessarily have to pass all the parameters, and I need to transfer only those on which I want to filter out. Please help me to solve this problem
WHERE (#ts IS NULL OR [ts] = #ts)
and (#username IS NULL OR [username] = #username)
and (#ip IS NULL OR [ip] = #ip)
and (#my_category IS NULL OR [my_category] = #my_category)
and (#my_name IS NULL OR [my_name] = #my_name)
and (#nm1_name IS NULL OR [nm1_name] = #nm1_name)
and (#param IS NULL OR [param] = #param)
and (#short_descr IS NULL OR [short_descr] = #short_descr)
EDIT:
I've seen in comment to other answer that you are passing blank string instead of NULLs. In that case you need to handle them instead (or in addition) to NULLs
WHERE (#ts IS NULL OR #ts = '' OR [ts] = #ts)
and (#username IS NULL OR #username = '' OR [username] = #username)
and (#ip IS NULL OR #ip = '' OR [ip] = #ip)
and (#my_category IS NULL OR #my_category = '' OR [my_category] = #my_category)
and (#my_name IS NULL OR #my_name = '' OR [my_name] = #my_name)
and (#nm1_name IS NULL OR #nm1_name = '' OR [nm1_name] = #nm1_name)
and (#param IS NULL OR #param = '' OR [param] = #param)
and (#short_descr IS NULL OR #short_descr = '' OR [short_descr] = #short_descr)
You're setting your parameters to NULL when you're not using the related filter, right?
So you could use a query like this:
WHERE isnull(#ts, [ts]) = [ts]
and isnull(#username, [username]) = [username]
and isnull(#ip, [ip]) = [ip]
and isnull(#my_category, [my_category]) = [my_category]
and isnull(#my_name, [my_name]) = [my_name]
and isnull(#nm1_name, [nm1_name]) = [nm1_name]
and isnull(#param, [param]) = [param]
and isnull(#short_descr, [short_descr]) = [short_descr]
option (recompile)
I advocate using option (recompile) in such a scenario
EDIT:
with '' instead of NULL
WHERE #ts in ('', [ts])
and #username in ('', [username])
and #ip in ('', [ip])
and #my_category in ('', [my_category])
and #my_name in ('', [my_name])
and #nm1_name in ('', [nm1_name])
and #param in ('', [param])
and #short_descr in ('', [short_descr])
(more readable than using OR each and every time and it doesn't require recompile*)
(*) as parameters will not be sniffed anyway
set val=isnull(FLD380,'Null')
*i need to write same statement for SPACE(''). like this
set val=space(FLD380,'Space')
What you're specifically asking for is a user-defined function. Note this syntax is for SQL Server.
CREATE FUNCTION IsSpace (
#check_expression NVARCHAR(max),
#replacement_value NVARCHAR(max)
)
RETURNS NVARCHAR(MAX)
BEGIN
IF #check_expression = N''
RETURN #replacement_value
RETURN #check_expression
END
Which can be called like this:
set #val = IsSpace(FLD380, N'Space')
Alternatively, here's the SQL Server syntax for Explosion Pills' response.
SET #val =
CASE
WHEN FLD380 = '' THEN 'Space'
ELSE ISNULL(FLD380, 'null')
END
SET val= CASE WHEN FLD380 = '' THEN 'Space' ELSE
(CASE WHEN FLD380 IS NULL THEN 'Null' END) END
See fiddle
SET val = IF(FLD380 = '', 'Space', IFNULL(FLD380, 'Null'))
how about using COALESCE
SET val = IF(TRIM(FLD380) = '', 'SPACE', COALESCE(FLD380, 'NULL'))