I have reduced this sample to the absolute necessary minimum. So I'm aware, that it does not make sense :-)
I know, I can select XML from a table with the following query:
select id as [Direction/#Id],
direction as [Direction]
from devicepdo
for xml path('')
The result will look like this:
<Direction Id="1">I</Direction>
<Direction Id="2">O</Direction>``
<Direction Id="3">I</Direction>
<Direction Id="4">O</Direction>
....
The column direction always contains I or O, and I want to change the enclosing XML Tag depending on the column value.
My result should look like this:
<In Id="1">I</In>
<Out Id="2">O</Out>``
<In Id="3">I</In>
<Out Id="4">O</Out>
....
All my tries to use a variable or colum in the "AS" clause failed.
In my query, the "Direction" in "as [Direction/#Id]" should be variable depending on the column value.
Is this possible? Any hints or ideas?
If all attributes are null, and the contents is null, no tag will be generated. You can use this fact to generate different types of tags depending on values in each row.
select
-- If direction is I then generate an In tag
case when direction = 'I' then id else null end as [In/#Id],
case when direction = 'I' then direction else null end as [In],
-- If direction is O then generate an Out tag
case when direction = 'O' then id else null end as [Out/#Id],
case when direction = 'O' then direction else null end as [Out]
from devicepdo
for xml path('')
Effectively you have expressions for all possible tags, but for rows where a type of tag is not desired, use a case statement to make the expression null.
Related
I have a where conditional
where
pnumber in ('mem1234', 'mem2345','mem8978')
I need a substring without the mem in this where conditional. There are a couple hundred strings in this where conditional.
What is the syntax for this?
In order to manipulate the data you will first need to insert it into a temp table/ table variable and then depending on how consistant your data is you could try the following:
DECLARE #pNumbers TABLE (item varchar(20))
insert into #pNumbers values('mem1234'),('mem2345'),('mem8978')
select
REPLACE(item, 'mem', '') AS ReplaceMethod ,
SUBSTRING(item, 4, 4) AS SubstringMethod,
RIGHT(item,LEN(item) - 3) AS Right_LenMethod
FROM #pNumbers
You would then add one of them methods to a subquery in the WHERE
WHERE
pnumber IN ( SELECT REPLACE(item, 'mem', '') FROM #pNumbers )
Or as others have stated, you could open the csv in an external program and find and replace but atleast you have options
is there a chance to use optional parameters in report builder?
for example: i have a query with 3 parameters
#Pa1 date
#Pa2 date
#Pa3 varchar(3)
if i run View report without inform one of then i got the message:
Select a value for the parameter #Pa3 (for example)
is it possible?
I tried to use a empty field but i got no data
select a.legajo,c.nombres,e.Descripcion,CONVERT (char(10), a.fecha, 103) as Fecha,a.hora as ENTRADA,
b.hora as SALIDA,
DATEDIFF(HOUR,a.hora,b.hora) as Horas_trabajadas,
c.hor_x_jor Horas_jornada,
DATEDIFF(HOUR,a.hora,b.hora) -hor_x_jor as Diferencia
from fichadas_in a, fichadas_out b, empleados c,sucursales d,Clasificacion e
where a.Legajo=b.Legajo
and a.fecha=b.fecha
and a.fecha between #fecha1 and #fecha2
and d.codigo=#sucursal
and a.legajo=c.legajo
and c.CCO=d.Codigo
and e.Codigo=c.Clasif
Order by a.fecha,legajo
Allow Null Values or Blank values for your parameter.
As already mentioned you need to select ALLOW BLANK VALUES, and ALLOW NULL VALUE.. But you also have to ensure your SQL knows what to do with those VALUES in your WHERE clause.
AND (
((#Pa3 IS NOT NULL AND #Pa3 != '') AND d.codigo = #Pa3)
OR
((#Pa3 IS NULL OR #Pa3 = '') AND d.codigo LIKE '%'))
)
There are other ways to do this, but make sure you account for those values/lack of values.
For the date range, I would recommend declaring another variable that calculates what the date value is before running the SELECT statement.. Create a variable that is calculates what the value is if the value is blank, null, or entered.
The variable may go in to #Pa1 but then calculates into #fecha1, then in the WHERE clause you us #fecha1.
I am writing a stored procedure in SQL where i have a scenario that fetch all record if parameter is null or fetch matching record if parameter is not null. In this case, i always use ISNULL function like that:
table.value = ISNULL(#param,table.value)
But in this case if value is not null, it works fine, but if value is null then it fetch all record except those where table.value is null. So i searched and found a solution here answered by sII. but i don't understand the statement
#param IS NULL OR value= #param
It works fine for me but i am unable to understand? How it works? Thanks in advance for answer.
Below is my understanding about ALL IF NULL Statement.
Case 1: If the parameter #param IS NULL.
In this case the All if NULL statement becomes like this,
NULL IS NULL OR value= #param.
Here the left part of the OR statement becomes True, So records will fetch according to that part. so the query becomes,
SELECT *FROM TABLE WHERE NULL IS NULL which is same as
SELECT *FROM TABLE. So it will fetch all the records.
Case 2: If the parameter #param have a value (say value = 1)
In this case the All if NULL statement becomes like this,
1 IS NULL OR value= 1.
Here the left part of the OR statement becomes False, So records will fetch according to the right part.
So the query becomes,
SELECT *FROM TABLE WHERE value= 1.
Hope you understand Now..
I'm building an application that needs to allow the user to filter a data table according to different filters. So, the user will have three different filter posibilites but he might use only one, or two or the three of them at the same tame.
So, let's say I have the following columns on the table:
ID (int) PK
Sede (int)
Programa (int)
Estado (int)
All of those columns will store numbers, integers. The "ID" column is the primary key, "Sede" stores 1 or 2, "Programa" is any number between 1 and 15, and "Estado" will store numbers between 1 and 13.
The user may filter the data stored in the table using any of those filters (Sede, Programa or Estado). But the might, as well, use two filters, or the three of them at the same time.
The idea is that this application works like the data filters on Excel. I created a simulated table on excel to show what I want to achieve:
This first image shows the whole table, without applying any filter.
Here, the user selected a filter for "Sede" and "Programa" but leaved the "Estado" filter empty. So the query returns the values that are equal to the filter, but leaves the "Estado" filter open, and brings all the records, filering only by "Sede" (1) and "Programa" (6).
In this image, the user only selected the "Estado" filter (5), so it brings all the records that match this criteria, it doesn't matter if "Sede" or "Programa" are empty.
If I use a SELECT clasuse with a WHERE on it, it will work, but only if the three filters have a value:
DECLARE #sede int
DECLARE #programa int
DECLARE #estado int
SET #sede = '1'
SET #programa = '5'
SET #estado = '12'
SELECT * FROM [dbo].[Inscripciones]
WHERE
([dbo].[Inscripciones].[Sede] = #sede)
AND
([dbo].[Inscripciones].[Programa] = #programa)
AND
([dbo].[Inscripciones].[Estado] = #estado)
I also tryed changing the "AND" for a "OR", but I can't get the desired result.
Any help will be highly appreciated!! Thanks!
common problem: try using coalesce on the variable and for the 2nd value use the field name you're comparing to. Be careful though; Ensure it's NULL and not empty string being passed!
What this does is take the first non-null value of the variable passed in or the value you're comparing to.. Thus if the value passed in is null the comparison will always return true.
WHERE
[dbo].[Inscripciones].[Sede] = coalesce(#sede, [dbo].[Inscripciones].[Sede])
AND
[dbo].[Inscripciones].[Programa] = coalesce(#programa, [dbo].[Inscripciones].[Programa])
AND
[dbo].[Inscripciones].[Estado] = coalesce(#estado, [dbo].[Inscripciones].[Estado])
If sede is null and programa and estado are populated the compare would look like...
?=? (or 1=1)
?=programa variable passed in
?=Estado variable passed in
Boa Sorte!
Thank you all for your anwers. After reading the article posted in the comments by #SeanLange I was finally able to achieve what was needed. Using a CASE clause in the WHERE statement solves the deal. Here's the code:
SELECT
*
FROM [dbo].[Inscripciones]
WHERE
([dbo].[Inscripciones].[Sede] = (CASE WHEN #sede = '' THEN [dbo].[Inscripciones].[Sede] ELSE #sede END))
AND
([dbo].[Inscripciones].[Programa] = (CASE WHEN #programa = '' THEN [dbo].[Inscripciones].[Programa] ELSE #programa END))
AND
([dbo].[Inscripciones].[Estado] = (CASE WHEN #estado = '' THEN [dbo].[Inscripciones].[Estado] ELSE #estado END))
AND
([dbo].[Inscripciones].[TipoIngreso] = (CASE WHEN #tipoingreso = '' THEN [dbo].[Inscripciones].[TipoIngreso] ELSE #tipoingreso END))
Thanks again!!
I'm beating my head against the wall here... can't figure out a way to pull this off.
Here's my setup:
My table has a column for the date something was completed. If it was never completed, the field is null. Simple enough.
On the front end, I have a checkbox that defaults to "Only show incomplete entries". When only pulling incomplete entries, it's easy.
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL
But offering the checkbox option complicates things a great deal. My checkbox inputs a bit value: 1=only show incomplete, 0=show all.
The problem is, I can't use a CASE statement within the where clause, because an actual value uses "=" to compare, and checking null uses "IS". For example:
SELECT
*
FROM Sometable
WHERE Completed_Date IS <---- invalid syntax
CASE WHEN
...
END
SELECT
*
FROM Sometable
WHERE Completed_Date =
CASE WHEN #OnlyIncomplete = 1 THEN
NULL <----- this translates to "WHERE Completed_Date = NULL", which won't work.. I have to use "IS NULL"
...
END
Any idea how to accomplish this seemly easy task? I'm stumped... thanks.
...
WHERE #OnlyIncomplete = 0
OR (#OnlyIncomplete = 1 AND Completed_Date IS NULL)
Hmmm... I think what you want is this:
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL OR (#OnlyIncomplete = 0)
So that'll show Date=NULL plus, if OnlyIncomplete=0, Date != Null. Yeah, I think that's it.
If you still want to use a CASE function (although it may be overkill in this case) :
SELECT
*
FROM Sometable
WHERE 1 =
(CASE WHEN #OnlyIncomplete = 0 THEN 1
WHEN #OnlyIncomplete = 1 AND Completed_Date IS NULL THEN 1
END)