SQL Server stored procedure WHERE clause - sql

Need help with WHERE clause in this stored procedure.
How to write WHERE with this parameters and if any of these param contains specific value, then I need to get all values from that column ?
Sample if #post1 contains 1 then select values from that columns that are equals to 1.
But if #post1 contains 0 than select all values from that column. And that for all other parameters.
ALTER PROCEDURE [dbo].[spStavke]
#dat1 date,
#dat2 date,
#god int,
#post1 int,
#post2 int,
#post3 int
AS
BEGIN
SET NOCOUNT ON;
SELECT
[test1]
,[test2]
,[test3]
,[test3]
FROM
[PN].[dbo].[Stavke] AS stavke
LEFT JOIN
PN.dbo.Tip AS tip ON stavke.Vrsta = tip.id
LEFT JOIN
PN.dbo.Vrsta AS vrs ON stavke.Jedinica = vrs.id
END

SELECT
[test1]
,[test2]
,[test3]
,[test3]
FROM [PN].[dbo].[Stavke] as stavke
left join PN.dbo.Tip as tip on stavke.Vrsta=tip.id
left join PN.dbo.Vrsta as vrs on stavke.Jedinica = vrs.id
WHERE (#Post1 = 0 OR (#Post1 = 1 AND 1 IN( TEST1,TEST2,TEST3))
AND (#Post2 = 0 OR (#Post2 = 1 AND 1 IN( TEST1,TEST2,TEST3))

Related

How can I make the below change query dynamic for each table, I have my id column as common?

BEGIN TRANSACTION
DECLARE #currentVersion bigint = (SELECT TOP 1 LastVersion FROM VersionTracking WHERE TableName='Test1')
DECLARE #newVersion bigint = CHANGE_TRACKING_CURRENT_VERSION()
SELECT
CT.EmployeeID,
Test1.Name,
Test1.Position,
CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
Test1
RIGHT OUTER JOIN
CHANGETABLE(CHANGES dbo.Test1, #currentVersion) CT ON Test1.EmployeeID = CT.EmployeeID
UPDATE VersionTracking
SET LastVersion = #newVersion
WHERE TableName = 'Test1'
COMMIT
How to make the above query dynamic in case of multiple tables? So that we can use this for each of the table with SSIS packages or ADF

Update 1 table-col using 2 table-col from other table

Is it possible to update 1 column/field of my table using 2 column/field from other table?
i tried this query :
UPDATE TEMP_Quantity
SET SS = (SELECT Qty1, Qty2 FROM Table_Quantity
WHERE Id = #IdHolder AND ProductId = 7)
WHERE Id = #IdHolder
And Sql said this error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.`
SS = NVarchar (Because it can accept number or string base on the column that i will select)
can someone tell me the right way to do this? tia :)
Uhm... to answer your question, you can CONCAT both qty's
UPDATE t1
SET SS = CONCAT(t2.Qty1, t2.Qty2)
FROM TEMP_Quantity t1
INNER JOIN Table_Quantity t2 on t2.Id = t1.Id
WHERE t1.Id = #IdHolder
AND t2.ProductId = 7
But this just feels wrong.
Try this :
UPDATE TEMP_Quantity
SET SS = (SELECT CAST(Qty1 AS VARCHAR(10)) + CAST(Qty2 AS VARCHAR(10))
FROM Table_Quantity
WHERE Id = #IdHolder AND ProductId = 7)
WHERE Id = #IdHolder
You may use and examine the below script. I hope, it is usefull for you.
declare #qty1 int
declare #qty2 int
if object_id('tempdb..#dbDestination') is not null
drop table #dbDestination
create table #dbDestination(
Id int,
ss nvarchar(50)
)
if object_id('tempdb..#dbSource') is not null
drop table #dbSource
create table #dbSource(
Id int,
ProductId int,
qty1 int,
qty2 int
)
insert into #dbDestination(Id,ss) values (1,null),(2,null)
insert into #dbSource(Id,ProductId,qty1,qty2) values(1,7,10,3), (2,null,8,2)
UPDATE #dbDestination
SET SS = (
SELECT CAST(qty1 as nvarchar(50))+ cast(qty2 as nvarchar(50))
FROM #dbSource
WHERE Id = 1 AND ProductId = 7
)
WHERE Id = 1
select * from #dbDestination

How to create procedure with multiple string select query in sql?

I want to create procedure with multiple string select query.I want to insert data to table variable and join that temp table with other table.
I don't want to create temp table as real tables. I want to insert data to memory temp table.
Here is my procedure,
CREATE PROCEDURE sp_TempBatch
AS
DECLARE #TempBatchSerial TABLE
(
ID int,
Name nvarchar(200),
StockType nvarchar(50),
ItemNo nvarchar(50)
)
DECLARE #TempQuery as nvarchar(MAX)='',
#VendorQuery as nvarchar(MAX)=''
BEGIN
SET #TempQuery='SELECT ID,Name,'
IF StockType = '1'
BEGIN
SET #TempQuery += ' ''Batch'' as StockType,'
END
ELSE
BEGIN
SET #TempQuery += ' ''Serial'' as StockType,'
END
SET #TempQuery += 'ItemNo INTO #TempBatchSerial
FROM Stock'
EXEC (#TempQuery)
SET #VendorQuery+=' SELECT #TempBatchSerial.* FROM #TempBatchSerial
INNER JOIN Vendor
ON #TempBatchSerial.ID = Vendor.ID
INNER JOIN Partner
ON Vendor.parentid = Partner.syskey'
EXEC (#VendorQuery)
END
When execute procedure show error message of Must declare the table variable "#TempBatchSerial"
You have to refer to #tempBatchSerial via an Alias
That's the only way #tempTables can be referred or linked to.
SELECT T.* FROM #TempBatchSerial T
INNER JOIN Vendor
ON T.ID = Vendor.ID
INNER JOIN Partner
ON Vendor.parentid = Partner.syskey
If that doesn't work you can try to put the #tempTable in the #vendorQuery text.

Table Variable In a table Valued function

I am getting an error when trying to get this table valued function up. I have an error when I try to modify it. It is
Incorrect syntax near the keyword 'Declare'.
However when I use this outside of the function it all works great. So I was just wondering is there something I am missing or how should I be doing this. Thanks.
ALTER FUNCTION [dbo].[XXX]( #i_contactkey int,
#v_scope varchar(15),
#i_entrykey int = null,
#i_staffcontactkey int = null,
#d_startdate datetime,
#d_today datetime)
RETURNS TABLE
AS begin
Declare #temp as table
(contactkey int, contactkey1 int, rolekey1 int,contactkey2 int, rolekey2 int, relationshipid int)
insert into #temp (contactkey , contactkey1 , rolekey1 ,contactkey2 , rolekey2 , relationshipid )
select contactkey , contactkey1 , rolekey1 ,contactkey2 , rolekey2 , relationshipid
from contact clcon
LEFT JOIN contactassociation ca on ca.contactkey2 = clcon.contactkey where ca.rolekey1 in (4,5,6)
and ca.relationshipid = 181
and ca.activeind = 1
and ca.associationkey = (select top 1 associationkey
from contactassociation
where contactkey2 = clcon.contactkey and activeind = 1
and relationshipid = 181
and rolekey1 in (4,5,6)
order by begindate desc)
SELECT
clcon.contactkey'ClientId',
clcon.Stat'ClientStatus',
ctacct.optiondesc'account',
ctlvl.optiondesc'levelid',
(clcon.lastname+', '+clcon.firstname)'ClientName',
clcon.firstname'ClientFirstName',
clcon.lastname'ClientLastName',
clcon.addressline1'address1',
clcon.addressline2'address2',
clcon.city'city',
dbo.getcnfgoption(81,clcon.stateid,'D')'state',
clcon.zipcode'zipcode',
clcon.mainphone'mainphone',
cgcon.contactkey'cgkey',(cgcon.firstname+' '+cgcon.lastname)'CGName',
cgcon.firstname'CGFirstName',
cgcon.lastname'CGLastName',
cgcon.addressline1'cgaddressline1',
cgcon.addressline2'cgaddressline2',
cgcon.city'cgcity',
dbo.getcnfgoption(81,cgcon.stateid,'D')'cgstate',
cgcon.zipcode'cgzipcode',
cgcon.mainphone'cgmainphone',
dbo.getClientAltCGKeys_JSON(clcon.contactkey,'J')'AltCGsJSON',
--dbo.getClientAltCGKeys(clcon.contactkey,'C')'AltCGNames',
--dbo.getClientAltCGKeys(clcon.contactkey,'L')'altcgnamekeyslast',
--dbo.getClientAltCGKeys(clcon.contactkey,'A')'altcgkeysaddress',
dbo.getClientEventCount(clcon.contactkey, 'M', #d_startdate, #d_today) 'MLOA',
dbo.getClientEventCount(clcon.contactkey, 'N', #d_startdate, #d_today) 'NMLOA',
dbo.getClientEventCount(clcon.contactkey, 'A', #d_startdate, #d_today) 'Alts',
dbo.getClientEventCount(clcon.contactkey, 'S', #d_startdate, #d_today ) 'Suspension',
dbo.getClientEventCountAnnual(clcon.contactkey, 'C') 'MissingNotes',
-- dbo.getContactVerificationStatus(clcon.contactkey, 'D')'clverification',
-- dbo.getContactVerificationStatus(cgcon.contactkey, 'D')'cgverification',
ed1.eventkey 'mdskey',
dbo.getCnfgTableOption(54,ed1.eventstatusid,'D')'mdsstatus',
ed1.ScheduledDate 'NextMDS',
ed2.eventkey 'pockey',
dbo.getCnfgTableOption(54,ed2.eventstatusid,'D')'pocstatus',
ed2.ScheduledDate 'NextPoC',
ed3.eventkey 'hvkey',
dbo.getCnfgTableOption(54,ed3.eventstatusid,'D')'hvsstatus',
ed3.ScheduledDate 'NextHV',
ed4.eventkey 'medlistkey',
dbo.getCnfgTableOption(54,ed4.eventstatusid,'D')'medstatus',
ed4.ScheduledDate 'NextMedList',
ed5.eventkey 'semikey',
dbo.getCnfgTableOption(54,ed5.eventstatusid,'D')'semistatus',
ed5.ScheduledDate 'NextSemi',
ed6.eventkey'placementkey',
ed6.startdate'placementstart',
ed6.enddate'placementend',
[dbo].[getClientCMName](clcon.contactkey)'cmname',
[dbo].[getClientRNName](clcon.contactkey)'rnname',
[dbo].[getClientCMKey](clcon.contactkey)'cmkey',
[dbo].[getClientRNKey](clcon.contactkey)'rnkey',
alertcount=(SELECT COUNT(eventalertkey) FROM veventalert WHERE alerttype='Alert' AND clientkey=clcon.contactkey AND viewedind=0 AND contactkey=COALESCE(#i_staffcontactkey,#i_contactkey)),
alertkey=(SELECT MAX(eventalertkey) FROM veventalert WHERE alerttype='Alert' AND clientkey=clcon.contactkey AND viewedind=0 AND contactkey=COALESCE(#i_staffcontactkey,#i_contactkey)),
msgcount=(SELECT COUNT(eventalertkey) FROM veventalert WHERE alerttype='Message' AND clientkey=clcon.contactkey AND viewedind=0 AND cgkey=cgcon.contactkey),
msgkey=(SELECT MAX(eventalertkey) FROM veventalert WHERE alerttype='Message' AND clientkey=clcon.contactkey AND viewedind=0 AND cgkey=cgcon.contactkey),
clcp.birthdate
FROM (select dbo.getcontactstatus(contactkey,'ts')'Stat',* from contact where dbo.getcontactstatus(contactkey,'ts') is not null ) clcon
INNER JOIN contactrole cr
ON (clcon.contactkey = cr.contactkey)
--Find caregiver contact info
LEFT JOIN contactassociation ca on ca.contactkey2 = clcon.contactkey and ca.rolekey1 in (4,5,6)
and ca.relationshipid = 181 and ca.activeind = 1
and ca.associationkey = (select max(associationkey)
from contactassociation
where contactkey2 = clcon.contactkey and activeind = 1
and relationshipid = 181
and rolekey1 in (4,5,6))
LEFT JOIN contact cgcon
ON cgcon.contactkey = ca.contactkey1 and cgcon.activeind = 1
LEFT JOIN contactbu cbu
ON (clcon.contactkey = cbu.contactkey)
/*Account/Lvl Information*/
LEFT JOIN contactprofile clcp
ON (clcon.contactkey=clcp.contactkey)
LEFT JOIN cnfgtableoption ctlvl
ON (clcp.svclevelid = ctlvl.tableoptionkey)
LEFT JOIN cnfgtableoption ctacct
ON (clcp.accountid = ctacct.tableoptionkey)
LEFT JOIN eventdefinition ed1 /* MDS */
ON (clcon.contactkey=ed1.contactkey AND ed1.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 181, 'MINOPEN'))
LEFT JOIN eventdefinition ed2 /* POC */
ON (clcon.contactkey=ed2.contactkey AND ed2.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 120, 'MINOPEN'))
LEFT JOIN eventdefinition ed3 /* HV */
ON (clcon.contactkey=ed3.contactkey AND ed3.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 341, 'MINOPEN'))
LEFT JOIN eventdefinition ed4 /* MED */
ON (clcon.contactkey=ed4.contactkey AND ed4.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 178, 'MINOPEN'))
LEFT JOIN eventdefinition ed5 /* SEMI */
ON (clcon.contactkey=ed5.contactkey AND ed5.eventkey=dbo.getContactEventByWftask(clcon.contactkey, 122, 'MINOPEN'))
LEFT JOIN eventdefinition ed6 /* Placement */
ON (clcon.contactkey=ed6.contactkey AND ed6.wftaskkey = 49
AND ed6.eventstatusid = 16
AND ed6.activeind = 1
AND ed6.enddate = (select MAX(enddate) from eventdefinition
where contactkey = clcon.contactkey and wftaskkey = 49
and activeind = 1
and eventstatusid = 16))
WHERE
--Contact info
cr.rolekey = 8
AND cbu.entrykey = #i_entrykey
--and dbo.getcontactstatus (clcon.contactkey,'TS') not in ('Closed','Discharged')
and clcon.Stat not in ('Closed')
and clcon.activeind=1
-- filter by branch entrykey (if param exists)
--order by clcon.lastname,clcon.firstname
When you're using multiple statements in a function and returning a table, i.e. a Table-Valued User-Defined Function, you need a certain syntax, something like:
CREATE FUNCTION dbo.MyFunction(#ID int)
RETURNS #Mytable TABLE
(
-- Columns returned by the function
ID int PRIMARY KEY NOT NULL,
-- (Other columns as required)
)
AS
BEGIN
--Various statements to populate #Mytable
RETURN; -- Returns #Mytable
END
See Table-Valued User-Defined Functions for more information.
If you have a function that just has RETURNS TABLE with no definition of the table being returned, this is an Inline User-Defined Function.
Inline user-defined functions are a subset of user-defined functions
that return a table data type. Inline functions can be used to achieve
the functionality of parameterized views.
See Inline User-Defined Functions.
The syntax for this is like:
CREATE FUNCTION dbo.MyFunction(#ID int)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM MyTable
WHERE ID = #ID
);
Here you don't define the table being returned and the body of the function can only be one SELECT statement.
At the moment your code is somewhere between the two; you need to get this to work as the first option, i.e. the Table-Valued User-Defined Function; start by defining the table being returned in the RETURNS clause and go from there.
You have invalid function declaration. When returning table you should specify variable name that will hold your table, so your header may look like:
ALTER FUNCTION [dbo].[XXX](.....)
RETURNS #temp TABLE (contactkey int, contactkey1 int, rolekey1 int,contactkey2 int, rolekey2 int, relationshipid int)
AS
begin
...
You need to define the table's columns in the RETURNS statement.

SQL WHERE ... IN clause with possibly null parameter

I am having some problems with my WHERE clause (using SQL 2008) . I have to create a stored procedure that returns a list of results based on 7 parameters, some of which may be null. The ones which are problematic are #elements, #categories and #edu_id. They can be a list of ids, or they can be null. You can see in my where clause that my particular code works if the parameters are not null. I'm not sure how to code the sql if they are null. The fields are INT in the database.
I hope my question is clear enough. Here is my query below.
BEGIN
DECLARE #elements nvarchar(30)
DECLARE #jobtype_id INT
DECLARE #edu_id nvarchar(30)
DECLARE #categories nvarchar(30)
DECLARE #full_part bit
DECLARE #in_demand bit
DECLARE #lang char(2)
SET #jobtype_id = null
SET #lang = 'en'
SET #full_part = null -- full = 1, part = 0
SET #elements = '1,2,3'
SET #categories = '1,2,3'
SET #edu_id = '3,4,5'
select
jobs.name_en,
parttime.fulltime_only,
jc.cat_id category,
je.element_id elem,
jt.name_en jobtype,
jobs.edu_id minEdu,
education.name_en edu
from jobs
left join job_categories jc
on (jobs.job_id = jc.job_id)
left join job_elements je
on (jobs.job_id = je.job_id)
left join job_type jt
on (jobs.jobtype_id = jt.jobtype_id)
left join education
on (jobs.edu_id = education.edu_id)
left join
(select job_id, case when (jobs.parttime_en IS NULL OR jobs.parttime_en = '') then 1 else 0 end fulltime_only from jobs) as parttime
on jobs.job_id = parttime.job_id
where [disabled] = 0
and jobs.jobtype_id = isnull(#jobtype_id,jobs.jobtype_id)
and fulltime_only = isnull(#full_part,fulltime_only)
-- each of the following clauses should be validated to see if the parameter is null
-- if it is, the clause should not be used, or the SELECT * FROM ListToInt... should be replaced by
-- the field evaluated: ie if #elements is null, je.element_id in (je.element_id)
and je.element_id IN (SELECT * FROM ListToInt(#elements,','))
and jc.cat_id IN (SELECT * FROM ListToInt(#categories,','))
and education.edu_id IN (SELECT * FROM ListToInt(#edu_id,','))
order by case when #lang='fr' then jobs.name_fr else jobs.name_en end;
END
Something like
and (#elements IS NULL OR je.element_id IN
(SELECT * FROM ListToInt(#elements,',')))
and (#categories IS NULL OR
jc.cat_id IN (SELECT * FROM ListToInt(#categories,',')))
....
should do the trick
je.element_id IN (SELECT * FROM ListToInt(#elements,',')) OR #elements IS NULL
that way for each one
Have you tried explicitly comparing to NULL?
and (#elements is null or je.element_id IN (SELECT * FROM ListToInt(#elements,','))
And so on.