Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Tuesday, March 27, 2012

Clear the resultset during batch processing

Hello SQL Experts,
I have a Batch of Select statments which runs in a while loop and i use
the @.@.rowcount to get the rows returned to manipulate furture.
the problem is after some time in the middle of the process i get the
below error
"The query has exceeded the maximum number of result sets that can be
displayed in the results grid. Only the first 100 result sets are
displayed in the grid."
Is there a way by which i can stop the results being displayed in the
message tab or clear the diplayed result or result set as said in the
error messge. as after the error message the task stops on it own.
i dont know if there is any thing using SET statment
/soni
hi,
This means essentially you do not need these results generated by the SQLs?
is this the case? can you send some sample SQLs so something can be
suggested close to your needs.
rgds
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164947463.012890.94570@.f1g2000cwa.googlegrou ps.com...
> Hello SQL Experts,
> I have a Batch of Select statments which runs in a while loop and i use
> the @.@.rowcount to get the rows returned to manipulate furture.
> the problem is after some time in the middle of the process i get the
> below error
>
> "The query has exceeded the maximum number of result sets that can be
> displayed in the results grid. Only the first 100 result sets are
> displayed in the grid."
> Is there a way by which i can stop the results being displayed in the
> message tab or clear the diplayed result or result set as said in the
> error messge. as after the error message the task stops on it own.
> i dont know if there is any thing using SET statment
> /soni
>
|||Hello Falik,
Thanks for showing a helping hand
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:[vbcol=seagreen]
> hi,
> This means essentially you do not need these results generated by the SQLs?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegrou ps.com...
|||Hello Falik,
Thanks for showing a helping hand
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:[vbcol=seagreen]
> hi,
> This means essentially you do not need these results generated by the SQLs?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegrou ps.com...
|||Hi Soni,
can u produce the sampel data , expected result and SQLs (may use the pubs
database for this), as I can;t understand the why count is not used or group
by can;t be used for this?
as down the line we need to stop the unwanted result-set generated by the
selects......
thnx
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164955286.981884.286430@.j44g2000cwa.googlegr oups.com...
> Hello Falik,
> Thanks for showing a helping hand
> something like this
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'A'
> -- this will return 2100 rows
> Select @.ARank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'B'
> -- this will return 1000 rows
> Select @.BRank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'C'
> -- this will return 1000 rows
> Select @.CRank = @.@.rowcount
> this way the code is runing in a while loop logic. I cannot use count
> () function as there is data mismatch because of Duplicate records in
> some table.
> /soni
> Falik Sher wrote:
>
sqlsql

Clear the resultset during batch processing

Hello SQL Experts,
I have a Batch of Select statments which runs in a while loop and i use
the @.@.rowcount to get the rows returned to manipulate furture.
the problem is after some time in the middle of the process i get the
below error
"The query has exceeded the maximum number of result sets that can be
displayed in the results grid. Only the first 100 result sets are
displayed in the grid."
Is there a way by which i can stop the results being displayed in the
message tab or clear the diplayed result or result set as said in the
error messge. as after the error message the task stops on it own.
i dont know if there is any thing using SET statment
/sonihi,
This means essentially you do not need these results generated by the SQLs?
is this the case? can you send some sample SQLs so something can be
suggested close to your needs.
rgds
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...
> Hello SQL Experts,
> I have a Batch of Select statments which runs in a while loop and i use
> the @.@.rowcount to get the rows returned to manipulate furture.
> the problem is after some time in the middle of the process i get the
> below error
>
> "The query has exceeded the maximum number of result sets that can be
> displayed in the results grid. Only the first 100 result sets are
> displayed in the grid."
> Is there a way by which i can stop the results being displayed in the
> message tab or clear the diplayed result or result set as said in the
> error messge. as after the error message the task stops on it own.
> i dont know if there is any thing using SET statment
> /soni
>|||Hello Falik,
Thanks for showing a helping hand :)
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:
> hi,
> This means essentially you do not need these results generated by the SQLs?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...
> > Hello SQL Experts,
> >
> > I have a Batch of Select statments which runs in a while loop and i use
> > the @.@.rowcount to get the rows returned to manipulate furture.
> >
> > the problem is after some time in the middle of the process i get the
> > below error
> >
> >
> > "The query has exceeded the maximum number of result sets that can be
> > displayed in the results grid. Only the first 100 result sets are
> > displayed in the grid."
> >
> > Is there a way by which i can stop the results being displayed in the
> > message tab or clear the diplayed result or result set as said in the
> > error messge. as after the error message the task stops on it own.
> >
> > i dont know if there is any thing using SET statment
> >
> > /soni
> >|||Hello Falik,
Thanks for showing a helping hand :)
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:
> hi,
> This means essentially you do not need these results generated by the SQLs?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...
> > Hello SQL Experts,
> >
> > I have a Batch of Select statments which runs in a while loop and i use
> > the @.@.rowcount to get the rows returned to manipulate furture.
> >
> > the problem is after some time in the middle of the process i get the
> > below error
> >
> >
> > "The query has exceeded the maximum number of result sets that can be
> > displayed in the results grid. Only the first 100 result sets are
> > displayed in the grid."
> >
> > Is there a way by which i can stop the results being displayed in the
> > message tab or clear the diplayed result or result set as said in the
> > error messge. as after the error message the task stops on it own.
> >
> > i dont know if there is any thing using SET statment
> >
> > /soni
> >|||Hi Soni,
can u produce the sampel data , expected result and SQLs (may use the pubs
database for this), as I can;t understand the why count is not used or group
by can;t be used for this'
as down the line we need to stop the unwanted result-set generated by the
selects......
thnx
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164955286.981884.286430@.j44g2000cwa.googlegroups.com...
> Hello Falik,
> Thanks for showing a helping hand :)
> something like this
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'A'
> -- this will return 2100 rows
> Select @.ARank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'B'
> -- this will return 1000 rows
> Select @.BRank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'C'
> -- this will return 1000 rows
> Select @.CRank = @.@.rowcount
> this way the code is runing in a while loop logic. I cannot use count
> () function as there is data mismatch because of Duplicate records in
> some table.
> /soni
> Falik Sher wrote:
>> hi,
>> This means essentially you do not need these results generated by the
>> SQLs?
>> is this the case? can you send some sample SQLs so something can be
>> suggested close to your needs.
>> rgds
>> Falik
>>
>> <chandresh.x.soni@.sonyericsson.com> wrote in message
>> news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...
>> > Hello SQL Experts,
>> >
>> > I have a Batch of Select statments which runs in a while loop and i use
>> > the @.@.rowcount to get the rows returned to manipulate furture.
>> >
>> > the problem is after some time in the middle of the process i get the
>> > below error
>> >
>> >
>> > "The query has exceeded the maximum number of result sets that can be
>> > displayed in the results grid. Only the first 100 result sets are
>> > displayed in the grid."
>> >
>> > Is there a way by which i can stop the results being displayed in the
>> > message tab or clear the diplayed result or result set as said in the
>> > error messge. as after the error message the task stops on it own.
>> >
>> > i dont know if there is any thing using SET statment
>> >
>> > /soni
>> >
>

Clear the resultset during batch processing

Hello SQL Experts,
I have a Batch of Select statments which runs in a while loop and i use
the @.@.rowcount to get the rows returned to manipulate furture.
the problem is after some time in the middle of the process i get the
below error
"The query has exceeded the maximum number of result sets that can be
displayed in the results grid. Only the first 100 result sets are
displayed in the grid."
Is there a way by which i can stop the results being displayed in the
message tab or clear the diplayed result or result set as said in the
error messge. as after the error message the task stops on it own.
i dont know if there is any thing using SET statment
/sonihi,
This means essentially you do not need these results generated by the SQLs?
is this the case? can you send some sample SQLs so something can be
suggested close to your needs.
rgds
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...
> Hello SQL Experts,
> I have a Batch of Select statments which runs in a while loop and i use
> the @.@.rowcount to get the rows returned to manipulate furture.
> the problem is after some time in the middle of the process i get the
> below error
>
> "The query has exceeded the maximum number of result sets that can be
> displayed in the results grid. Only the first 100 result sets are
> displayed in the grid."
> Is there a way by which i can stop the results being displayed in the
> message tab or clear the diplayed result or result set as said in the
> error messge. as after the error message the task stops on it own.
> i dont know if there is any thing using SET statment
> /soni
>|||Hello Falik,
Thanks for showing a helping hand
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:[vbcol=seagreen]
> hi,
> This means essentially you do not need these results generated by the SQLs
?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...|||Hello Falik,
Thanks for showing a helping hand
something like this
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'A'
-- this will return 2100 rows
Select @.ARank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'B'
-- this will return 1000 rows
Select @.BRank = @.@.rowcount
Select T1.issue, T2,Project
from Issue T1, Project T2...
Where T1.Rank = 'C'
-- this will return 1000 rows
Select @.CRank = @.@.rowcount
this way the code is runing in a while loop logic. I cannot use count
() function as there is data mismatch because of Duplicate records in
some table.
/soni
Falik Sher wrote:[vbcol=seagreen]
> hi,
> This means essentially you do not need these results generated by the SQLs
?
> is this the case? can you send some sample SQLs so something can be
> suggested close to your needs.
> rgds
> Falik
>
> <chandresh.x.soni@.sonyericsson.com> wrote in message
> news:1164947463.012890.94570@.f1g2000cwa.googlegroups.com...|||Hi Soni,
can u produce the sampel data , expected result and SQLs (may use the pubs
database for this), as I can;t understand the why count is not used or group
by can;t be used for this'
as down the line we need to stop the unwanted result-set generated by the
selects......
thnx
Falik
<chandresh.x.soni@.sonyericsson.com> wrote in message
news:1164955286.981884.286430@.j44g2000cwa.googlegroups.com...
> Hello Falik,
> Thanks for showing a helping hand
> something like this
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'A'
> -- this will return 2100 rows
> Select @.ARank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'B'
> -- this will return 1000 rows
> Select @.BRank = @.@.rowcount
> Select T1.issue, T2,Project
> from Issue T1, Project T2...
> Where T1.Rank = 'C'
> -- this will return 1000 rows
> Select @.CRank = @.@.rowcount
> this way the code is runing in a while loop logic. I cannot use count
> () function as there is data mismatch because of Duplicate records in
> some table.
> /soni
> Falik Sher wrote:
>

Thursday, March 22, 2012

Clause where in [Select... ?

Hi,
I would like that instrucion bellow bring me all solicitations which
quotation is in the select clause where in.
It gives me error at this part in [Select Cotacao from Cotacoes Where
Pedido = P1]
Thanks,
Vilmar
Select * From
Solicitations
Where
Sc_Cotacao in [Select Cotacao from Cotacoes Where Pedido = P1]
Solicitations
Code CodeQuotation
S1 C1
S2 C1
S3 C1
S4 C2
S5 C2
S6 C2
S7 C3
S8 C3
S9 C3
Quotation
Code CodeRequest
C1 P1
C2 P1
C3 P1
Pedidos
P1
P2
P3
««««««««»»»»»»»»»»»»»»
Vlmar Brazão de Oliveira
Desenvolvimento Web
HI-TECSounds like P1 should be a string literal
Select * From
> Solicitations
> Where
> Sc_Cotacao in [Select Cotacao from Cotacoes Where Pedido = 'P1']
Wayne Snyder MCDBA, SQL Server MVP
Computer Education Services Corporation (CESC), Charlotte, NC
(Please respond only to the newsgroups.)
I support the Professional Association for SQL Server
(www.sqlpass.org)
"Vilmar Brazão de Oliveira" <suporte@.hitecnet.com.br> wrote in message
news:OAXMBnxwDHA.1912@.TK2MSFTNGP09.phx.gbl...
> Hi,
> I would like that instrucion bellow bring me all solicitations which
> quotation is in the select clause where in.
> It gives me error at this part in [Select Cotacao from Cotacoes Where
> Pedido = P1]
> Thanks,
> Vilmar
> Select * From
> Solicitations
> Where
> Sc_Cotacao in [Select Cotacao from Cotacoes Where Pedido = P1]
>
> Solicitations
> Code CodeQuotation
> S1 C1
> S2 C1
> S3 C1
> S4 C2
> S5 C2
> S6 C2
> S7 C3
> S8 C3
> S9 C3
> Quotation
> Code CodeRequest
> C1 P1
> C2 P1
> C3 P1
> Pedidos
> P1
> P2
> P3
> ««««««««»»»»»»»»»»»»»»
> Vlmar Brazão de Oliveira
> Desenvolvimento Web
> HI-TEC
>|||You will get better responses if you post the actual error message.
Assuming that your query is the one posted, the select statement used with
IN should be bounded with parentheses, not brackets
"Vilmar Brazão de Oliveira" <suporte@.hitecnet.com.br> wrote in message
news:OAXMBnxwDHA.1912@.TK2MSFTNGP09.phx.gbl...
> Hi,
> I would like that instrucion bellow bring me all solicitations which
> quotation is in the select clause where in.
> It gives me error at this part in [Select Cotacao from Cotacoes Where
> Pedido = P1]
> Thanks,
> Vilmar
> Select * From
> Solicitations
> Where
> Sc_Cotacao in [Select Cotacao from Cotacoes Where Pedido = P1]
>
> Solicitations
> Code CodeQuotation
> S1 C1
> S2 C1
> S3 C1
> S4 C2
> S5 C2
> S6 C2
> S7 C3
> S8 C3
> S9 C3
> Quotation
> Code CodeRequest
> C1 P1
> C2 P1
> C3 P1
> Pedidos
> P1
> P2
> P3
> ««««««««»»»»»»»»»»»»»»
> Vlmar Brazão de Oliveira
> Desenvolvimento Web
> HI-TEC
>|||Thank you everybody!
It was switch square brackets by parentheses.
Regards,
Vilmar
Brazil
"Scott Morris" <bogus@.bogus.com> escreveu na mensagem
news:uzakf7xwDHA.2520@.TK2MSFTNGP10.phx.gbl...
> You will get better responses if you post the actual error message.
> Assuming that your query is the one posted, the select statement used with
> IN should be bounded with parentheses, not brackets
> "Vilmar Brazão de Oliveira" <suporte@.hitecnet.com.br> wrote in message
> news:OAXMBnxwDHA.1912@.TK2MSFTNGP09.phx.gbl...
> > Hi,
> > I would like that instrucion bellow bring me all solicitations which
> > quotation is in the select clause where in.
> > It gives me error at this part in [Select Cotacao from Cotacoes Where
> > Pedido = P1]
> > Thanks,
> > Vilmar
> >
> > Select * From
> > Solicitations
> > Where
> > Sc_Cotacao in [Select Cotacao from Cotacoes Where Pedido = P1]
> >
> >
> > Solicitations
> > Code CodeQuotation
> > S1 C1
> > S2 C1
> > S3 C1
> > S4 C2
> > S5 C2
> > S6 C2
> > S7 C3
> > S8 C3
> > S9 C3
> >
> > Quotation
> > Code CodeRequest
> > C1 P1
> > C2 P1
> > C3 P1
> >
> > Pedidos
> > P1
> > P2
> > P3
> >
> > ««««««««»»»»»»»»»»»»»»
> > Vlmar Brazão de Oliveira
> > Desenvolvimento Web
> > HI-TEC
> >
> >
>

Classic ASP in Report Manager

Can I run classic asp pages in the report manager?
I'm implementing a multi-value select report which works fine using a
standard html page. I want to serive my values from a database however
and am therefor using asp. The asp page will display in the report
manager but the code will not run.
Thoughts?
Thanks!I had uploaded the asp page to the report manager. Keeping the page
outside report manager did the trick.
-J|||You would need to add the correct script mappings to the Report Manager
virtual directory. We do not add .asp mappings by default.
--
Brian Welcker
Group Program Manager
Microsoft SQL Server Reporting Services
This posting is provided "AS IS" with no warranties, and confers no rights.
"Jim" <emailjeffp@.yahoo.com> wrote in message
news:1114279221.384407.35000@.z14g2000cwz.googlegroups.com...
>I had uploaded the asp page to the report manager. Keeping the page
> outside report manager did the trick.
> -J
>

Tuesday, March 20, 2012

Clarification on NULL values in the records.

Hi All
Please write me the reason for
SQL:
--
select * from table1
where Required <> 'Y'
the result set is empty.
Table Schema is:
--
CREATE TABLE [dbo].[Table1] (
[Names] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,
[Required] [nvarchar] (10) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
Insert Statement is is:
--
insert into table1 ([Names],Required)
values('Test1',null)
insert into table1 ([Names],Required)
values('Test2','Y')
insert into table1 ([Names],Required)
values('Test3',null)
insert into table1 ([Names],Required)
values('Test4','Y')
insert into table1 ([Names],Required)
values('Test5',null)
Is there any option I need to get the appropriate result
set?
B'coz my result set expected is
Test1 NULL
Test3 NULL
Test5 NULLWhy are you allowing NULLs? That's the problem, you can't say NULL is not
equal to 'Y'... since the definition of NULL is unknown, then it very may
well by 'Y' ...
How about making it NOT NULL DEFAULT 'N'?
Or make your query WHERE COALESCE(Required, 'N') = 'N'?
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Ana" <anonymous@.discussions.microsoft.com> wrote in message
news:a96401c43652$5032ef30$a601280a@.phx.gbl...
> Hi All
> Please write me the reason for
> SQL:
> --
> select * from table1
> where Required <> 'Y'
> the result set is empty.
> Table Schema is:
> --
> CREATE TABLE [dbo].[Table1] (
> [Names] [nvarchar] (50) COLLATE
> SQL_Latin1_General_CP1_CI_AS NULL ,
> [Required] [nvarchar] (10) COLLATE
> SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> Insert Statement is is:
> --
> insert into table1 ([Names],Required)
> values('Test1',null)
> insert into table1 ([Names],Required)
> values('Test2','Y')
> insert into table1 ([Names],Required)
> values('Test3',null)
> insert into table1 ([Names],Required)
> values('Test4','Y')
> insert into table1 ([Names],Required)
> values('Test5',null)
> Is there any option I need to get the appropriate result
> set?
> B'coz my result set expected is
> Test1 NULL
> Test3 NULL
> Test5 NULL|||Hi Aaron Bertrand
Thanks for your clear information.Now I undestand.
Thanks once again
Ana.
>--Original Message--
>Why are you allowing NULLs? That's the problem, you
can't say NULL is not
>equal to 'Y'... since the definition of NULL is unknown,
then it very may
>well by 'Y' ...
>How about making it NOT NULL DEFAULT 'N'?
>Or make your query WHERE COALESCE(Required, 'N') = 'N'?
>--
>Aaron Bertrand
>SQL Server MVP
>http://www.aspfaq.com/
>
>
>"Ana" <anonymous@.discussions.microsoft.com> wrote in
message
>news:a96401c43652$5032ef30$a601280a@.phx.gbl...
>> Hi All
>> Please write me the reason for
>> SQL:
>> --
>> select * from table1
>> where Required <> 'Y'
>> the result set is empty.
>> Table Schema is:
>> --
>> CREATE TABLE [dbo].[Table1] (
>> [Names] [nvarchar] (50) COLLATE
>> SQL_Latin1_General_CP1_CI_AS NULL ,
>> [Required] [nvarchar] (10) COLLATE
>> SQL_Latin1_General_CP1_CI_AS NULL
>> ) ON [PRIMARY]
>> GO
>> Insert Statement is is:
>> --
>> insert into table1 ([Names],Required)
>> values('Test1',null)
>> insert into table1 ([Names],Required)
>> values('Test2','Y')
>> insert into table1 ([Names],Required)
>> values('Test3',null)
>> insert into table1 ([Names],Required)
>> values('Test4','Y')
>> insert into table1 ([Names],Required)
>> values('Test5',null)
>> Is there any option I need to get the appropriate result
>> set?
>> B'coz my result set expected is
>> Test1 NULL
>> Test3 NULL
>> Test5 NULL
>
>.
>|||Answered in .programming.
Please don't multi-post.
--
David Portas
SQL Server MVP
--sqlsql

Monday, March 19, 2012

Choosing one record over another

How would I select one record and not the another related record in one
Select statement?
I have regular prices that I want to display on most days and promotional
prices on particular days (christmas, summer etc) where I don't want to
display the regular price if I am displaying the promotional price.
I have a table that has 2 types of records in it.
One record is a normal ticket price on a ship. The other record is a
promotional price for that ship.
If it is a Regular Price, there will be null values in the PromoPriceID,
StartDate and End Date (as these are only used for the promotional prices).
If it is a Promotional Price there will be a Null Value in ShipName (as I
would get that from the regular record). The PromoPriceID would contain the
Regular records ShipPricingID (so that it could get the name of the ship and
so that we would know not to display that records regular price). The
StartDate and EndDate would have the date range the promotional prices ran
for.
Here is a test file setup with the display of all the records.
****************************************
************************************
******************************
drop table shipPricing
create table shipPricing
(
ShipPricingID int Identity Not Null,
ShipName varChar(50) Null,
PromoPriceID int Null,
Price Money Not Null,
StartDate smalldatetime Null,
EndDate smalldatetime Null
)
insert shipPricing(ShipName,Price) values ('Sea Witch',1500)
insert shipPricing(PromoPriceID,Price,StartDate
,EndDate) values
(Scope_Identity(),1300,'12/01/05','12/31/05')
insert shipPricing(ShipName,Price) values ('Southern Cross',2200)
insert shipPricing(PromoPriceID,Price,StartDate
,EndDate) values
(Scope_Identity(),2050,'12/15/05','12/31/05')
select ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID, Price
= Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) from shipPricing
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
1 Sea Witch NULL 1,500.00
NULL NULL
2 NULL 1
1,300.00 12/01/05 12/31/05
3 Southern Cross NULL 2,200.00
NULL NULL
4 NULL 3
2,050.00 12/15/05 12/31/05
****************************************
************************************
****************************************
**
What I want to do is have a Select statement that would give me back the
prices available for a particular date (Select ... where date = some date).
If it is a promotion I don't want to show the regular price and I would
like it to say something like "Promo".
For example:
If I want the prices for 11/15/01 I should get something like:
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
1 Sea Witch NULL 1,500.00
NULL NULL
3 Southern Cross NULL 2,200.00
NULL NULL
If I want prices for 12/05/05, I should get something like:
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
2 Sea Witch 1
1,300.00 12/01/05 12/31/05 Promo
3 Southern Cross NULL 2,200.00
NULL NULL
If I want prices for 12/18/05, I should get something like:
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
2 Sea Witch 1
1,300.00 12/01/05 12/31/05 Promo
4 Southern Cross 3 2,050.00
12/15/05 12/31/05 Promo
I can't figure out how to select one record and not the other in one Select
statement.
Thanks,
Tomyou could do it with a simple if exists statement, like so:
-- let's assume you've got some kind of variable with your Date value
in it
DECLARE @.date datetime
IF EXISTS (SELECT * FROM shipPricing
WHERE @.date > StartDate AND @.date < EndDate)
SELECT * FROM shipPricing WHERE @.date > StartDate AND @.date < EndDate
ELSE
SELECT * FROM shipPricing WHERE StartDate IS NULL AND EndDate IS NULL
if the exists is true, you won't likely be taxed for the second query,
because the rows will already be cached from the if condition test. so
i'm pretty sure performance-wise you'll only be running 1 query,
essentially. also, you can simply replace * with whatever you want to
return, and since the promo stuff is in its own query, you can throw in
a 'Promo' value in for kicks.|||also, having the condition of one entity versus another being
determined by the presence or absense of values in a field seems a
little odd to me. if it's not a huge conversion, i would consider
migrating this data into two tables: shipPricingStandard, and
shipPricingPromo. that way your queries would look more like:
IF EXISTS (SELECT * FROM shipPricingPromo
WHERE @.date > StartDate AND @.date < EndDate)
SELECT * FROM shipPricingPromo WHERE @.date > StartDate AND @.date <
EndDate
ELSE
SELECT * FROM shipPricingStandard
not sure why, but it seems like a clearer division of what seem like
two similar, but separate entities. but that's probably open to debate,
and more cosmetic than anything.
hope this helps,
jason|||"jason" <iaesun@.yahoo.com> wrote in message
news:1124995465.591667.36420@.g14g2000cwa.googlegroups.com...
> you could do it with a simple if exists statement, like so:
> -- let's assume you've got some kind of variable with your Date value
> in it
> DECLARE @.date datetime
> IF EXISTS (SELECT * FROM shipPricing
> WHERE @.date > StartDate AND @.date < EndDate)
> SELECT * FROM shipPricing WHERE @.date > StartDate AND @.date < EndDate
> ELSE
> SELECT * FROM shipPricing WHERE StartDate IS NULL AND EndDate IS NULL
>
This was the problem I had.
The problem is that you can either get the Promo prices (those with dates)
or regular prices (those without dates). The problem is that I want to
either a regular price OR a promotional price for both ships.
Here are the results if you add in dates you can see the problem. In the
first 2 it would either be on or the other for those dates, but the last
date should have the regular price for the Sea Witch and the promo price for
the other. Also I need to grab the name of the ship from the regular price
record if a promo price.
****************************************
************************************
***************************************
declare @.date smalldatetime
select @.date = '11/01/05'
IF EXISTS (SELECT * FROM shipPricing
WHERE @.date > StartDate AND @.date < EndDate)
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE @.date >
StartDate AND @.date < EndDate
ELSE
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE StartDate
IS NULL AND EndDate IS NULL
ShipPricingID ShipName PromoPriceID Price StartDate
EndDate
-- -- -- -- -- --
--
1 Sea Witch NULL 1,500.00
NULL NULL
3 Southern Cross NULL 2,200.00
NULL NULL
****************************************
************************************
****************************************
**
****************************************
************************************
*************************************
declare @.date smalldatetime
select @.date = '12/16/05'
IF EXISTS (SELECT * FROM shipPricing
WHERE @.date > StartDate AND @.date < EndDate)
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE @.date >
StartDate AND @.date < EndDate
ELSE
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE StartDate
IS NULL AND EndDate IS NULL
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
2 NULL 1
1,300.00 12/01/05 12/31/05
4 NULL 3
2,050.00 12/15/05 12/31/05
****************************************
************************************
****************************************
****
****************************************
************************************
****************************************
****
declare @.date smalldatetime
select @.date = '12/03/05'
IF EXISTS (SELECT * FROM shipPricing
WHERE @.date > StartDate AND @.date < EndDate)
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE @.date >
StartDate AND @.date < EndDate
ELSE
SELECT ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
SubString(Convert(varChar,EndDate,1),1,1
2) FROM shipPricing WHERE StartDate
IS NULL AND EndDate IS NULL
ShipPricingID ShipName PromoPriceID Price
StartDate EndDate
-- -- -- -- --
--
--
2 NULL 1
1,300.00 12/01/05 12/31/05
****************************************
************************************
****************************************
*****
Thanks,
Tom
> if the exists is true, you won't likely be taxed for the second query,
> because the rows will already be cached from the if condition test. so
> i'm pretty sure performance-wise you'll only be running 1 query,
> essentially. also, you can simply replace * with whatever you want to
> return, and since the promo stuff is in its own query, you can throw in
> a 'Promo' value in for kicks.
>|||"jason" <iaesun@.yahoo.com> wrote in message
news:1124995909.532864.267610@.g47g2000cwa.googlegroups.com...
> also, having the condition of one entity versus another being
> determined by the presence or absense of values in a field seems a
> little odd to me. if it's not a huge conversion, i would consider
> migrating this data into two tables: shipPricingStandard, and
> shipPricingPromo. that way your queries would look more like:
The reason I didn't pick 2 tables is the data is essentially the same except
for type of record as well as the dates. I could also add a type code
field, but I can do that by testing for the shipPricingID (if nothing there
it is a regular price) as well as the dates (again if nothing there it is a
regular record).
Tom
> IF EXISTS (SELECT * FROM shipPricingPromo
> WHERE @.date > StartDate AND @.date < EndDate)
> SELECT * FROM shipPricingPromo WHERE @.date > StartDate AND @.date <
> EndDate
> ELSE
> SELECT * FROM shipPricingStandard
> not sure why, but it seems like a clearer division of what seem like
> two similar, but separate entities. but that's probably open to debate,
> and more cosmetic than anything.
> hope this helps,
> jason
>|||t - try this:
declare @.dt datetime
set @.dt = cast('12/18/05' as datetime)
select
case
when @.dt between s2.startdate and s2.enddate then s2.ShipPricingID
else s.ShipPricingID
end as ShipPricingID,
ShipName = substring(s.ShipName,1,20),
case
when @.dt between s2.startdate and s2.enddate then s2.PromoPriceID
else s.PromoPriceID
end as PromoPriceID,
case
when @.dt between s2.startdate and s2.enddate then s2.Price
else s.Price
end as Price,
case
when @.dt between s2.startdate and s2.enddate then s2.StartDate
else s.StartDate
end as StartDate,
case
when @.dt between s2.startdate and s2.enddate then s2.EndDate
else s.EndDate
end as EndDate,
case
when @.dt between s2.startdate and s2.enddate then 'PROMO'
else NULL
end as Promo
from shipPricing s inner join shipPricing s2 on s.ShipPricingID =
s2.PromoPriceID
"tshad" <tscheiderich@.ftsolutions.com> wrote in message
news:O84VJtZqFHA.2276@.TK2MSFTNGP10.phx.gbl...
> How would I select one record and not the another related record in one
> Select statement?
> I have regular prices that I want to display on most days and promotional
> prices on particular days (christmas, summer etc) where I don't want to
> display the regular price if I am displaying the promotional price.
> I have a table that has 2 types of records in it.
> One record is a normal ticket price on a ship. The other record is a
> promotional price for that ship.
> If it is a Regular Price, there will be null values in the PromoPriceID,
> StartDate and End Date (as these are only used for the promotional
prices).
> If it is a Promotional Price there will be a Null Value in ShipName (as I
> would get that from the regular record). The PromoPriceID would contain
the
> Regular records ShipPricingID (so that it could get the name of the ship
and
> so that we would know not to display that records regular price). The
> StartDate and EndDate would have the date range the promotional prices ran
> for.
> Here is a test file setup with the display of all the records.
>
****************************************
************************************
******************************kred">
> drop table shipPricing
> create table shipPricing
> (
> ShipPricingID int Identity Not Null,
> ShipName varChar(50) Null,
> PromoPriceID int Null,
> Price Money Not Null,
> StartDate smalldatetime Null,
> EndDate smalldatetime Null
> )
> insert shipPricing(ShipName,Price) values ('Sea Witch',1500)
> insert shipPricing(PromoPriceID,Price,StartDate
,EndDate) values
> (Scope_Identity(),1300,'12/01/05','12/31/05')
> insert shipPricing(ShipName,Price) values ('Southern Cross',2200)
> insert shipPricing(PromoPriceID,Price,StartDate
,EndDate) values
> (Scope_Identity(),2050,'12/15/05','12/31/05')
> select ShipPricingID,ShipName = substring(ShipName,1,20),PromoPriceID,
Price
> = Substring(Convert(varChar,Price,1),1,12)
,StartDate =
> Substring(Convert(varChar,StartDate,1),1
,12),EndDate =
> SubString(Convert(varChar,EndDate,1),1,1
2) from shipPricing
> ShipPricingID ShipName PromoPriceID Price
> StartDate EndDate
> -- -- -- -- --
--
> --
> 1 Sea Witch NULL 1,500.00
> NULL NULL
> 2 NULL 1
> 1,300.00 12/01/05 12/31/05
> 3 Southern Cross NULL 2,200.00
> NULL NULL
> 4 NULL 3
> 2,050.00 12/15/05 12/31/05
>
****************************************
************************************
****************************************
**
> What I want to do is have a Select statement that would give me back the
> prices available for a particular date (Select ... where date = some
date).
> If it is a promotion I don't want to show the regular price and I would
> like it to say something like "Promo".
> For example:
> If I want the prices for 11/15/01 I should get something like:
> ShipPricingID ShipName PromoPriceID Price
> StartDate EndDate
> -- -- -- -- --
--
> --
> 1 Sea Witch NULL 1,500.00
> NULL NULL
> 3 Southern Cross NULL 2,200.00
> NULL NULL
> If I want prices for 12/05/05, I should get something like:
> ShipPricingID ShipName PromoPriceID Price
> StartDate EndDate
> -- -- -- -- --
--
> --
> 2 Sea Witch 1
> 1,300.00 12/01/05 12/31/05 Promo
> 3 Southern Cross NULL 2,200.00
> NULL NULL
> If I want prices for 12/18/05, I should get something like:
> ShipPricingID ShipName PromoPriceID Price
> StartDate EndDate
> -- -- -- -- --
--
> --
> 2 Sea Witch 1
> 1,300.00 12/01/05 12/31/05 Promo
> 4 Southern Cross 3
2,050.00
> 12/15/05 12/31/05 Promo
> I can't figure out how to select one record and not the other in one
Select
> statement.
> Thanks,
> Tom
>|||This is not a table. It has no key, uses proprietary data types, etc.
This one table has more not null-able columns than the payroll for a
major auto manufacture.
Are you aware that "camelCase" adds 8-12% more time to reading code?
The eye jumps to the uppercase letter, then back to the front of the
word.
Is there really a ship with a CHAR(50) name or were you just too lazy
to pick a proper size? With the complete lack of data integrity in
this schema, you will get one.
Let's get back to the basics of an RDBMS. Rows are not records; fields
are not columns; tables are not files. IDENTITY cannot ever be a key
**by definition**, which I would hope you have learned by now.
CREATE TABLE VoyagePricing -- were you pricing the ships or the
trips?
(ship_name VARCHAR(30) NOT NULL -- I would use a ship code
CHECK (ship_name IN (..)),
promo_name CHAR(10) DEFAULT 'Regular Price' NOT NULL,
trip_price DECIMAL(7,2) NOT NULL,
start_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
end_date DATETIME NOT NULL,
CHECK (start_date < end_date),
PRIMARY KEY (ship_name, start_date)
);
Notice the use of duration ranges. Promos are nested inside the
regular fare ranges.
That is really bad business! You can show them what they are saving
with this query.
SELECT ship_name, promo_name, trip_price
FROM VoyagePricing AS P
WHERE @.my_date BETWEEN start_date AND end_date;
This will give you both the promo and regular prices. I assume that we
give the customer the lower price.
SELECT ship_name, MIN(trip_price)
FROM VoyagePricing
WHERE @.my_date BETWEEN start_date AND end_date
GROUP BY ship_name;
You keep posting the worst code of anyone in this newsgroup. Can you
get your boss to pay for a basic RDBMS course for you and the other
programmers?
A little over a year ago, I got to watch incompetent RDBMS programmers
like you kill children in Africa by messing up a medical supply system.|||Nice Rant.
First of all, and you seem to miss the point, this is not my actual table.
If you look closely (and I know this is difficult), there are NO ship
details. That is because "I MADE THIS TABLE UP JUST TO IRRITATE YOU".
The table has exactly what I felt was necessary to illustrate my problem and
allow others to quickly run it (if they want) without wasting anyones time.
I am not worrying about keys here, I am not worried about indexes, I am not
worried about the size of the Ship name (anywhy would you think a 50 was not
a proper size for a ship name - too big, too little')
Everyone here has been great and I appreciate the time that people take to
help others. I would not presume on their time by not putting only the
necessary elements to illustrate the problem. I'm not sure where
nullable/non nullable, camelCase, Pascal, Uppercase, lower case, variable
size etc. has anything to do with the question I was asking.
BTW, you weren't incorrect in your assessment as to what I was looking for.
VC got it. What happened to you? This was the reason I made the table as
spartan as possible as well as multiple examples to show what I was looking
for. You obviously missed it.
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1124999165.137822.47650@.g44g2000cwa.googlegroups.com...
> This is not a table. It has no key, uses proprietary data types, etc.
> This one table has more not null-able columns than the payroll for a
> major auto manufacture.
>
It is a table.
A table must have keys?
And you even call it a table (one that has more not nullable columns ...).
It has 2 BTW, one being identity column, which by definition would not be
nullable anyway.
create table shipPricing
(
ShipPricingID int Identity Not Null,
ShipName varChar(50) Null,
PromoPriceID int Null,
Price Money Not Null,
StartDate smalldatetime Null,
EndDate smalldatetime Null
)
What propriety data types?

> Are you aware that "camelCase" adds 8-12% more time to reading code?
> The eye jumps to the uppercase letter, then back to the front of the
> word.
>
Never seen that statistic. Where did you get that from?
Actually, I use camelCase for variable names (as do many). I also don't do
ship_names, I do ShipNames or shipNames. I never liked the underscore. But
that's just me.
You use ShipNames and ship_names style - but that's just you.

> Is there really a ship with a CHAR(50) name or were you just too lazy
> to pick a proper size? With the complete lack of data integrity in
> this schema, you will get one.
YUP.
schema? What schema? This is just a table (wait a minute, this isn't a
table) ! :)
> Let's get back to the basics of an RDBMS. Rows are not records; fields
> are not columns; tables are not files. IDENTITY cannot ever be a key
> **by definition**, which I would hope you have learned by now.
>
Cannot ever be a key'?
By what definition ?
Here is one I have read:
Definition: The primary key of a relational table uniquely identifies each
record in the table. It can either be a normal attribute that is guaranteed
to be unique (such as Social Security Number in a table with no more than
one record per person) or it can be generated by the DBMS (such as a
globally unique identifier, or GUID, in Microsoft SQL Server). Primary keys
may consist of a single attribute or multiple attributes in combination.
Does an Identity uniquely identify each record in the table?
Is it guaranteed to be unique? ( by definition)
Is it generated by the DBMS'?
Single attribute?

> CREATE TABLE VoyagePricing -- were you pricing the ships or the
> trips?
Why is that even a question and what does it have to do with the question?
Maybe I'm pricing the popcorn on the ship. What difference does it make?

> (ship_name VARCHAR(30) NOT NULL -- I would use a ship code
So would I, but I wanted to see the best way to get the name both from the
record that had the name and the Promo that didn't, but refered to the
record that had the name.

> CHECK (ship_name IN (..)),
> promo_name CHAR(10) DEFAULT 'Regular Price' NOT NULL,
Not really quite sure what you are doing here. There are 2 prices one
regular and one or more Promotional record that would display (instead of)
the regular price between the start and end dates (such as Chrismas in my
examples).

> trip_price DECIMAL(7,2) NOT NULL,
> start_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
> end_date DATETIME NOT NULL,
> CHECK (start_date < end_date),
> PRIMARY KEY (ship_name, start_date)
> );
> Notice the use of duration ranges. Promos are nested inside the
> regular fare ranges.
>
Not what I am trying to do. How does this handle multiple Promos'?
where is the Date Range for the Promos'

> That is really bad business! You can show them what they are saving
> with this query.
>
Bad Business? How about incorrect assessment of the question? or the
problem?

> SELECT ship_name, promo_name, trip_price
> FROM VoyagePricing AS P
> WHERE @.my_date BETWEEN start_date AND end_date;
> This will give you both the promo and regular prices. I assume that we
> give the customer the lower price.
>
Won't give them what I was trying to give them.

> SELECT ship_name, MIN(trip_price)
> FROM VoyagePricing
> WHERE @.my_date BETWEEN start_date AND end_date
> GROUP BY ship_name;
>
Also, won't give them what I was trying to give them. You have what I
needed above - how did you miss it' "If it is a promotion I don't want
to show the regular price and I would like it to say something like "Promo".
Where is that done with either of your examples'?
Ok, let me change the statement slightly.
"If the date that I am asking for is between any of the dates in the
Promotion records (row) for each Ship, display price for that row as well as
the ships name which you can get from the regular price record of that ship
and also pass back the word "Promo". If the date requested is not between
any of the dates in any of the Promotion records (row) for each ship, then
show the regular price and blank (null) instead of the word 'Promo'". In
any case, I should get 1 and only 1 record (row) back for each ship (either
a regular price or a promotional price)."

> You keep posting the worst code of anyone in this newsgroup.
Could be the case. If I was an expert, I wouldn't be asking questions.
<Can you
> get your boss to pay for a basic RDBMS course for you and the other
> programmers?
>
Already been there done that (many years ago). But I am also not an RDBMS
expert (as you may have gathered). And I am sure there are many ways to
skin a cat, as can be seen in this group. They can be done multiple ways
and still be right.

> A little over a year ago, I got to watch incompetent RDBMS programmers
> like you kill children in Africa by messing up a medical supply system.
Never been to Africa.
Tom|||"VC" <me@.here.com> wrote in message
news:XOCdnQobJZG1gpPeRVn-pw@.comcast.com...
> t - try this:
> declare @.dt datetime
> set @.dt = cast('12/18/05' as datetime)
> select
> case
> when @.dt between s2.startdate and s2.enddate then s2.ShipPricingID
> else s.ShipPricingID
> end as ShipPricingID,
> ShipName = substring(s.ShipName,1,20),
> case
> when @.dt between s2.startdate and s2.enddate then s2.PromoPriceID
> else s.PromoPriceID
> end as PromoPriceID,
> case
> when @.dt between s2.startdate and s2.enddate then s2.Price
> else s.Price
> end as Price,
> case
> when @.dt between s2.startdate and s2.enddate then s2.StartDate
> else s.StartDate
> end as StartDate,
> case
> when @.dt between s2.startdate and s2.enddate then s2.EndDate
> else s.EndDate
> end as EndDate,
> case
> when @.dt between s2.startdate and s2.enddate then 'PROMO'
> else NULL
> end as Promo
> from shipPricing s inner join shipPricing s2 on s.ShipPricingID =
> s2.PromoPriceID
Seems to do the job, except it shows Promotional records when it should show
Regular records and vice versa. I am sure it is just that one of the tests
is in reverse. Just need to look at it to see exactly what it does.
Just what I need, though.
Thanks a lot,
Tom
>
> "tshad" <tscheiderich@.ftsolutions.com> wrote in message
> news:O84VJtZqFHA.2276@.TK2MSFTNGP10.phx.gbl...
> prices).
> the
> and
> ****************************************
**********************************
**
> ******************************
> Price
> --
> ****************************************
**********************************
**
> ****************************************
**
> date).
> --
> --
> --
> 2,050.00
> Select
>|||tshad wrote:
> How would I select one record and not the another related record in one
> Select statement?
> I have regular prices that I want to display on most days and promotional
> prices on particular days (christmas, summer etc) where I don't want to
> display the regular price if I am displaying the promotional price.
> I have a table that has 2 types of records in it.
> One record is a normal ticket price on a ship. The other record is a
> promotional price for that ship.
>
Can I ask why you don't have two tables - one with just the ship
pricing (for the regular price - surely every ship must have a regular
price), and then a seperate table, foreign keying to the first,
containing the promotions? It seems like you're actually trying to
squeeze two tables into one, even though they don't share any
attributes?
Damien

Thursday, March 8, 2012

Children of the Children in MDX

Hi, all
I'm quite new to MDX.
What I'd like to know is weather it is possible to select all the children of the children of a given node in one-line query. Say we have [Driver].[All Drivers] dimension level. And I want to do something like "[Driver].[All Drivers].Children.Children" instead of obtaining the results with the use of "CrossJoin/Union" . E. g.:

{
Crossjoin({[Driver].[All Drivers].[564654 - Andrew]},
[ActivityPerDriverDailyEvents].[All Events].[Tue - 03/01/2006].Children)), Crossjoin({[Driver].[All Drivers].[564654 - Andrew]},
[ActivityPerDriverDailyEvents].[All Events].[Wed - 04/01/2006].Children)), Crossjoin({[Driver].[All Drivers].[564654 - Andrew]},
[ActivityPerDriverDailyEvents].[All Events].[Thu - 05/01/2006].Children)), Crossjoin({[Driver].[All Drivers].[564654 - Andrew]},
[ActivityPerDriverDailyEvents].[All Events].[Fri - 06/01/2006].Children))
}

Is there any other way of obtaining such a results without hardcoding the dates? Thank you.

Regards,
Roman

Roman,

I believe the function that you are looking for is "Generate".

Generate(<<Set1>>, <<Set2>>[,ALL])

Generate will take the members of the first set supplied to the function and apply them to the second set definition. It is almost like a for each loop in terms of the way it works. In the examples I have below using adventure works, Query 1 will return the US and the half years for 2003. Query 2 will return the US and the children of the half years (quarters) for 2003.

HTH,

- Steve

Query 1:

SELECT { [Measures].[Internet Sales Amount] } ON COLUMNS ,

{{[Customer].[Customer Geography].[Country].&[United States]} *

{[Date].[Calendar].[Calendar Year].&[2003].CHILDREN}} ON ROWS

FROM [Direct Sales]

CELL PROPERTIES VALUE, FORMATTED_VALUE, CELL_ORDINAL, ACTION_TYPE

Query 2:

SELECT { [Measures].[Internet Sales Amount] } ON COLUMNS ,

{{[Customer].[Customer Geography].[Country].&[United States]} *

Generate({[Date].[Calendar].[Calendar Year].&[2003].CHILDREN},

{[Date].[Calendar].CurrentMember.Children})} ON ROWS

FROM [Direct Sales]

CELL PROPERTIES VALUE, FORMATTED_VALUE, CELL_ORDINAL, ACTION_TYPE

|||Hi, Steve
In the dialect of MDX (Mondrian) I'm dealing with it would be impossible to use the Generate() method in such a context. So I used Descendants() method instead. And that piece of MDX code from previous post has turned to:

NonEmptyCrossJoin(
{[Driver].[All Drivers].[564654 - Andrew]},
{Descendants([ActivityPerDriverDailyEvents].[All Events])}
)

Thanks for your help!
Roman

Wednesday, March 7, 2012

CHECKSUM_AGG and BINARY_CHECKSUM performance problems

Gentlemen,

I am using the following query to get a list of grouped checksum data.

SELECT CAST(Field0_datetime AS INT),
CHECKSUM_AGG(BINARY_CHECKSUM(Field1_bigint, Field2_datetime,
Field3_datetime, Field4_bigint, Field5_bigint, CAST(Field6_float
Decimal(38,6)), Field7_datetime))
FROM Table1
WHERE Field0_datetime BETWEEN '2003-01-01' AND '2003-01-20'
GROUP BY CAST(Field0_datetime AS INT)

Please notice the used filter: from January 1 to January 20.
That query takes about 6 minutes do return the data. The result is 18
records.

However, when I execute the same query filtering BETWEEN '2003-01-01' and
'2003-01-10', this time it takes only 1 second to return data.
When I execute the query filtering BETWEEN '2003-01-10' and '2003-01-20' the
query takes another 1 second to return data.

So why 6 minutes to process them together??

The table have an index by Field0_datetime.

It contains about 1.5 millions records total, using around 1.7Gb of
diskspace, indexes included.

From 2003-01-01 and 2003-01-20, there are 11401 records selected. Don't look
like that much.

The situation is repeatable, I mean, if I execute the queries back and
again, they takes the about the same ammount of time to execute, so I don't
think this problem is related to cache or something like that.

I would appreciate any advice about what might be wrong with my situation.

Thanks a lot and kind regards,

Orly Junior
IT ProfessionalBy using the profiler, I found that while executing the first query (20 days
span), the system don't use the index. How it possible?

A simpler version of the query that causes the same problem is:

select checksum_agg(binary_checksum([dc])) from [table1] where [dc] between
'2003-01-01' and '2003-01-20'

The profiler reports it will be using a clustered index scan wich is
unacceptable since the table have a lot of records.

Why the hell it is not using the [dc] index ?? If a tight the criteria to
between a 10-day span it uses the index correctly.

Do you have any idea why is that happening?

Thanks in advance and best regards,

Orly Junior
IT Professional

"Orly Junior" <nomail@.nomail.com> wrote in message
news:42b0c9e6$0$32014$a729d347@.news.telepac.pt...
> Gentlemen,
> I am using the following query to get a list of grouped checksum data.
> SELECT CAST(Field0_datetime AS INT),
> CHECKSUM_AGG(BINARY_CHECKSUM(Field1_bigint, Field2_datetime,
> Field3_datetime, Field4_bigint, Field5_bigint, CAST(Field6_float
> Decimal(38,6)), Field7_datetime))
> FROM Table1
> WHERE Field0_datetime BETWEEN '2003-01-01' AND '2003-01-20'
> GROUP BY CAST(Field0_datetime AS INT)
> Please notice the used filter: from January 1 to January 20.
> That query takes about 6 minutes do return the data. The result is 18
> records.
> However, when I execute the same query filtering BETWEEN '2003-01-01' and
> '2003-01-10', this time it takes only 1 second to return data.
> When I execute the query filtering BETWEEN '2003-01-10' and '2003-01-20'
> the query takes another 1 second to return data.
> So why 6 minutes to process them together??
> The table have an index by Field0_datetime.
> It contains about 1.5 millions records total, using around 1.7Gb of
> diskspace, indexes included.
> From 2003-01-01 and 2003-01-20, there are 11401 records selected. Don't
> look like that much.
> The situation is repeatable, I mean, if I execute the queries back and
> again, they takes the about the same ammount of time to execute, so I
> don't think this problem is related to cache or something like that.
> I would appreciate any advice about what might be wrong with my situation.
> Thanks a lot and kind regards,
> Orly Junior
> IT Professional|||Orly Junior (nomail@.nomail.com) writes:
> By using the profiler, I found that while executing the first query (20
> days span), the system don't use the index. How it possible?

When you have a non-clustered index that can be used to compute a query,
SQL Server cannot always use this index blindly. If the selection is
small, the index is find. If the selection is large, the index spells
disaster. This is because every hit in the pages, requires an access to
the data pages. This can up with more pages reads, than use scanning the
table once.

Now, in your case, there are 11041 rows that matches the WHERE clause.
The table is 1.7 GB, which is 207 000 pages. Even if some of those
1.7 GB are indexes, the table scan is obviously more expensive.

But SQL Server does not build query plans from full knowledge, but from
statistics it has saved about the table. If this statistics is inaccurate
for some reason, the estimate may be incorrect. By default, SQL Server
does only sample data for its statistics.

You can try "UPDATE STATISTICS tbl WITH FULLSCAN" and see if this
has any effect. SQL Server will now look at all rows. However, it
saves data in a histogramme, so you may still lose accuracy. DBCC
SHOW_STATISTICS may give some information.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

checksum

It seems that the checksum function does not distinguish between positive
and negative decimals or floats. Is this by design? For example
select checksum(1.0)
select checksum(-1.0)
returns:
-1374215283
-1374215283Elmer Miller wrote:
> It seems that the checksum function does not distinguish between positive
> and negative decimals or floats. Is this by design? For example
> select checksum(1.0)
> select checksum(-1.0)
> returns:
> -1374215283
> -1374215283
That's right. CHECKSUM doesn't necessarily return distinct results for
different inputs.
SELECT CHECKSUM(N'ABC') AS ABC,CHECKSUM(N'ASH') AS ASH;
ABC ASH
-- --
1132495864 1132495864
(1 row(s) affected)
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||It is odd. I am trying to use checksum to build an index. The documentation
states that checksum is intended for the building of hash indexes.
However...
I have a table of approx 1.3 million rows and 25 columns (mixed types). I
ran the following statements:
select count(*) as vol, checksum(*) as Hash from <tablename> group by
checksum(*) order by vol desc
This returned 227 records that had the same check sums as another row in the
same table. No row was matched more than twice. This means that 0.01% of the
rows have the same check sums. I then took a look at the rows and they are
very different. They do have the same data types across the columns but there
is a 0.01% chance that my table returns the same checksum despite the data
within them being very different.
This means that I can't really use it as an index. Could there be another
way of creating an index from columns? perhaps an MD5 Hash?
thanks for any help on this.
"David Portas" wrote:
> Elmer Miller wrote:
> > It seems that the checksum function does not distinguish between positive
> > and negative decimals or floats. Is this by design? For example
> > select checksum(1.0)
> >
> > select checksum(-1.0)
> >
> > returns:
> >
> > -1374215283
> >
> > -1374215283
> That's right. CHECKSUM doesn't necessarily return distinct results for
> different inputs.
> SELECT CHECKSUM(N'ABC') AS ABC,CHECKSUM(N'ASH') AS ASH;
> ABC ASH
> -- --
> 1132495864 1132495864
> (1 row(s) affected)
>
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||Some other checksums will give you better results but basically no checksum
will guarantee you won't have collisions. Checksums are useful as indexes
just as hash functions are useful in building hash tables even though
uniqueness is not guaranteed. If I understood your statistics correctly,
you would return a maximum of two rows which is pretty good for 1.3 million
candidates. Presumably once you have narrowed the search to two or three
rows you can use some other means to get the exact row you want.
A checksum ensures that no two identical rows will return different
checksums but it doesn't ensure that the same checksum can't be returned
from different rows.
--
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
"Sharat Koya" <SharatKoya@.discussions.microsoft.com> wrote in message
news:4E79996B-27A5-46B5-8E9B-E3FFC68024D5@.microsoft.com...
> It is odd. I am trying to use checksum to build an index. The
> documentation
> states that checksum is intended for the building of hash indexes.
> However...
> I have a table of approx 1.3 million rows and 25 columns (mixed types). I
> ran the following statements:
> select count(*) as vol, checksum(*) as Hash from <tablename> group by
> checksum(*) order by vol desc
> This returned 227 records that had the same check sums as another row in
> the
> same table. No row was matched more than twice. This means that 0.01% of
> the
> rows have the same check sums. I then took a look at the rows and they are
> very different. They do have the same data types across the columns but
> there
> is a 0.01% chance that my table returns the same checksum despite the data
> within them being very different.
> This means that I can't really use it as an index. Could there be another
> way of creating an index from columns? perhaps an MD5 Hash?
> thanks for any help on this.
>
>
> "David Portas" wrote:
>> Elmer Miller wrote:
>> > It seems that the checksum function does not distinguish between
>> > positive
>> > and negative decimals or floats. Is this by design? For example
>> > select checksum(1.0)
>> >
>> > select checksum(-1.0)
>> >
>> > returns:
>> >
>> > -1374215283
>> >
>> > -1374215283
>> That's right. CHECKSUM doesn't necessarily return distinct results for
>> different inputs.
>> SELECT CHECKSUM(N'ABC') AS ABC,CHECKSUM(N'ASH') AS ASH;
>> ABC ASH
>> -- --
>> 1132495864 1132495864
>> (1 row(s) affected)
>>
>> --
>> David Portas, SQL Server MVP
>> Whenever possible please post enough code to reproduce your problem.
>> Including CREATE TABLE and INSERT statements usually helps.
>> State what version of SQL Server you are using and specify the content
>> of any error messages.
>> SQL Server Books Online:
>> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
>> --
>>

Friday, February 24, 2012

checking the SELECT statement for an SqlDataAdapter

I'm trying to pass a querystring to an SqlDataAdapter object. To check if the query is a valid SELECT statement, I simply use a try-catch. But dispite the try-catch it still accepts valid INSERT statements. However, in the parameterlist of the SqlDataAdapter the required parameter is a Transact SQL SELECT statement or a stored procedure... Am I doing something wrong?
 Here is my code:
try{ my_conn = conn_open(); da =new SqlDataAdapter(query, my_conn); da.Fill(result.resultDataset); my_conn.Dispose();}catch (Exception e){ result.errMsg ="Database Error: " + e.Message; result.success =false;}
Kehil

Kehil:

However, in the parameterlist of the SqlDataAdapter the required parameter is a Transact SQL SELECT statement or a stored procedure... Am I doing something wrong?

How do you know the parameterlist makes the SqlDataAdapter accpets only SELECT statement or SP? Actually when you create a SqlDataAdapter with a SqlCommand, the SqlCommand is used as SqlDataAdapter.SelectCommand, but this does not mean the SqlCommand must be a SELECT statement. If you want to validate SqlDataAdapter.SelectCommand, you need to validate the SqlCommand.CommandText to make sure it doesn't cotain any words like INSERT (but if there is a column named "INSERT" returned by a SELECT query, the statement will also considered invalid). So, such validation seems to make no sense.

Checking sysobjects for temp table

How can I check for the existence of a temp table before I attempt to drop
it?
Something like:
IF EXISTS( SELECT * FROM sysobjects WHERE Name = '#temp' )
DROP TABLE #temp
#temp exists but I cannot find a record for it in sysobjects. Neither can I
find it in tempdb (tempdb.dbo.sysobjects ).
Can anyone recommend how to handle this situation?Try:
if object_id('tempdb..#tmp') is not null
drop table #tmp
--
-Vishal
"David Frick" <dave@.frickcpa.com> wrote in message
news:uIYX89TTDHA.1992@.TK2MSFTNGP12.phx.gbl...
> How can I check for the existence of a temp table before I attempt to drop
> it?
> Something like:
> IF EXISTS( SELECT * FROM sysobjects WHERE Name = '#temp' )
> DROP TABLE #temp
> #temp exists but I cannot find a record for it in sysobjects. Neither can
I
> find it in tempdb (tempdb.dbo.sysobjects ).
> Can anyone recommend how to handle this situation?
>

Checking obligated values in different rows

Hi there!

I have a problem I can't get rid of... I hope anyone can help me with it!

For a room-booking application I need to select available rooms for a given
period. First I do the availability check which is no problem, than I need
to find out if there is a tariff available for every night of the given
period. If not, I will not show the room as 'available' in the system
because I can't make a tariff calculation.

All tariffs are entered in a table which can hold different night-tariffs
for different periods. The table looks like this:

========
CREATE TABLE [dbo].[TARIEVEN] (
[TARIEF_ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[FK_OBJECT_ID] [numeric](18, 0) NOT NULL ,
[STARTDATUM] [datetime] NULL ,
[EINDDATUM] [datetime] NULL ,
[TARIEF_PRIJS] [decimal](10, 2) NULL ,
) ON [PRIMARY]
GO

FK_OBJECT_ID is the Room ID
STARTDATUM is the startdate of a tariff period
EINDDATUM is the enddate of a tariff period
TARIEF_PRIJS is the tariff per night in the tariff period
========

What I do at the moment is:
---
SELECT fk_object_id FROM TARIEVEN
where ('15-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
AND ('16-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
AND ('17-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
---

This will work if all nights are in the same tariff period, but it will not
produce the right results if the tariffs are in different periods because no
single row contains a startdate and enddate in between which all dates are.
I can't use an OR statement because I absolutely need a tariff per night.

So, what my question is in short:
How can I for example select OBJECT 1 from the following table considering
that I want to return all rooms which have a tariff available for a period
from 15th of october to 17th of october?

------
FK_OBJECT_ID STARTDATUM EINDDATUM TARIEF_PRIJS
FK_OBJECT_ID STARTDATE ENDDATE TARIFF
1 10-oct-2004 16-oct-2004
100
1 17-oct-2004 18-oct-2004
125

In words: object 1 costs 100 per night in the period from 10 to 16 october
and 125 in the period from 17 to 18 october
------

I hope anyone can help me. Thanks a lot in advance!!

RobertI will assume that the Tarieven table won't contain overlapping dates, in
other words there can only be a single tariff per room per day.

DECLARE @.start_dt DATETIME, @.eind_dt DATETIME

/* The required date range: */
SET @.start_dt = '20041015'
SET @.eind_dt = '20041017'

SELECT @.start_dt, @.eind_dt,
fk_object_id, MIN(tarief_prijs) AS tarief_prijs
FROM Tarieven
WHERE einddatum >= @.start_dt
AND startdatum <= @.eind_dt
GROUP BY fk_object_id
HAVING MIN(tarief_prijs) = MAX(tarief_prijs)
AND MIN(startdatum) <= @.start_dt
AND MAX(einddatum) >= @.eind_dt

HAVING MIN(tarief_prijs) = MAX(tarief_prijs) ensures a single tariff.

The last two predicates exclude the case where the Tarieven table only
includes rows for part of the required period - in other words there was
only a single tariff for that room but it didn't cover the whole of the
required period.

--
David Portas
SQL Server MVP
--|||Brilliant!

Thanks a lot David!! You saved my life!

Checking obligated values in different rows

Hi there!

I have a problem I can't get rid of... I hope anyone can help me with it!

For a room-booking application I need to select available rooms for a given
period. First I do the availability check which is no problem, than I need
to find out if there is a tariff available for every night of the given
period. If not, I will not show the room as 'available' in the system
because I can't make a tariff calculation.

All tariffs are entered in a table which can hold different night-tariffs
for different periods. The table looks like this:

========
CREATE TABLE [dbo].[TARIEVEN] (
[TARIEF_ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[FK_OBJECT_ID] [numeric](18, 0) NOT NULL ,
[STARTDATUM] [datetime] NULL ,
[EINDDATUM] [datetime] NULL ,
[TARIEF_PRIJS] [decimal](10, 2) NULL ,
) ON [PRIMARY]
GO

FK_OBJECT_ID is the Room ID
STARTDATUM is the startdate of a tariff period
EINDDATUM is the enddate of a tariff period
TARIEF_PRIJS is the tariff per night in the tariff period
========

What I do at the moment is:
---
SELECT fk_object_id FROM TARIEVEN
where ('15-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
AND ('16-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
AND ('17-oct-2004' BETWEEN STARTDATUM AND EINDDATUM)
---

This will work if all nights are in the same tariff period, but it will not
produce the right results if the tariffs are in different periods because no
single row contains a startdate and enddate in between which all dates are.
I can't use an OR statement because I absolutely need a tariff per night.

So, what my question is in short:
How can I for example select OBJECT 1 from the following table considering
that I want to return all rooms which have a tariff available for a period
from 15th of october to 17th of october?

------
FK_OBJECT_ID STARTDATUM EINDDATUM TARIEF_PRIJS
FK_OBJECT_ID STARTDATE ENDDATE TARIFF
1 10-oct-2004 16-oct-2004
100
1 17-oct-2004 18-oct-2004
125

In words: object 1 costs 100 per night in the period from 10 to 16 october
and 125 in the period from 17 to 18 october
------

I hope anyone can help me. Thanks a lot in advance!!

RobertI will assume that the Tarieven table won't contain overlapping dates, in
other words there can only be a single tariff per room per day.

DECLARE @.start_dt DATETIME, @.eind_dt DATETIME

/* The required date range: */
SET @.start_dt = '20041015'
SET @.eind_dt = '20041017'

SELECT @.start_dt, @.eind_dt,
fk_object_id, MIN(tarief_prijs) AS tarief_prijs
FROM Tarieven
WHERE einddatum >= @.start_dt
AND startdatum <= @.eind_dt
GROUP BY fk_object_id
HAVING MIN(tarief_prijs) = MAX(tarief_prijs)
AND MIN(startdatum) <= @.start_dt
AND MAX(einddatum) >= @.eind_dt

HAVING MIN(tarief_prijs) = MAX(tarief_prijs) ensures a single tariff.

The last two predicates exclude the case where the Tarieven table only
includes rows for part of the required period - in other words there was
only a single tariff for that room but it didn't cover the whole of the
required period.

--
David Portas
SQL Server MVP
--|||Brilliant!

Thanks a lot David!! You saved my life!|||Hi David,

I hope I can use your brains again :-)

Your solution works perfectly except for one thing. If there is a gap in the
tariff information it will still return the object. Do you know of a
possibility to fix that?

Imagine the following information:

I'm trying to book a room from 12-oct-2004 to 21-oct-2004.

This is what the tariff table looks like
------
FK_OBJECT_ID STARTDATUM EINDDATUM TARIEF_PRIJS
FK_OBJECT_ID STARTDATE ENDDATE TARIFF
1 10-oct-2004 16-oct-2004
100
1 19-oct-2004 22-oct-2004
125
------

There is no tariff information for the nights of 17 and 18 october, so the
object should not be returned as a valid object (no price calculation can be
made for those nights). Is there a way to do this?

Hope you can help me again!

Robert|||First create a Calendar table to help with this one.

CREATE TABLE Calendar
(caldate DATETIME PRIMARY KEY)

Populate it:

INSERT INTO Calendar (caldate) VALUES ('20000101')

WHILE (SELECT MAX(caldate) FROM Calendar)<'20201231'
INSERT INTO Calendar (caldate)
SELECT DATEADD(D,DATEDIFF(D,'19991231',caldate),
(SELECT MAX(caldate) FROM Calendar))
FROM Calendar

Now you can do this:

SELECT @.start_dt, @.eind_dt,
fk_object_id, MIN(tarief_prijs) AS tarief_prijs
FROM Tarieven AS T
JOIN Calendar AS C
ON C.caldate
BETWEEN T.startdatum AND T.einddatum
AND C.caldate
BETWEEN @.start_dt AND @.eind_dt
GROUP BY fk_object_id
HAVING MIN(tarief_prijs) = MAX(tarief_prijs)
AND COUNT(DISTINCT C.caldate) > DATEDIFF(DAY,@.start_dt,@.eind_dt)

--
David Portas
SQL Server MVP
--|||Hi David,

I hope I can use your brains again :-)

Your solution works perfectly except for one thing. If there is a gap in the
tariff information it will still return the object. Do you know of a
possibility to fix that?

Imagine the following information:

I'm trying to book a room from 12-oct-2004 to 21-oct-2004.

This is what the tariff table looks like
------
FK_OBJECT_ID STARTDATUM EINDDATUM TARIEF_PRIJS
FK_OBJECT_ID STARTDATE ENDDATE TARIFF
1 10-oct-2004 16-oct-2004
100
1 19-oct-2004 22-oct-2004
125
------

There is no tariff information for the nights of 17 and 18 october, so the
object should not be returned as a valid object (no price calculation can be
made for those nights). Is there a way to do this?

Hope you can help me again!

Robert|||First create a Calendar table to help with this one.

CREATE TABLE Calendar
(caldate DATETIME PRIMARY KEY)

Populate it:

INSERT INTO Calendar (caldate) VALUES ('20000101')

WHILE (SELECT MAX(caldate) FROM Calendar)<'20201231'
INSERT INTO Calendar (caldate)
SELECT DATEADD(D,DATEDIFF(D,'19991231',caldate),
(SELECT MAX(caldate) FROM Calendar))
FROM Calendar

Now you can do this:

SELECT @.start_dt, @.eind_dt,
fk_object_id, MIN(tarief_prijs) AS tarief_prijs
FROM Tarieven AS T
JOIN Calendar AS C
ON C.caldate
BETWEEN T.startdatum AND T.einddatum
AND C.caldate
BETWEEN @.start_dt AND @.eind_dt
GROUP BY fk_object_id
HAVING MIN(tarief_prijs) = MAX(tarief_prijs)
AND COUNT(DISTINCT C.caldate) > DATEDIFF(DAY,@.start_dt,@.eind_dt)

--
David Portas
SQL Server MVP
--|||Great! Thanks for saving my life again :-)

Thanks a lot!|||Great! Thanks for saving my life again :-)

Thanks a lot!

Sunday, February 19, 2012

Checking null in select list

Hi all,
The following is in Select list, it returns null, how do I account if there
is a null in there or not
when writting this?
'1.) ' + dbo.TempERCP.Final_Diagnosis + ' 2.) ' +
dbo.TempERCP.Final_Diagnosis2 + ' 3.) ' + dbo.TempERCP.Final_Diagnosis3 as
[Final Diagnosis]
thanks
gvsee isnull() or coalesce() in BOL
gv wrote:
> Hi all,
> The following is in Select list, it returns null, how do I account if ther
e
> is a null in there or not
> when writting this?
> '1.) ' + dbo.TempERCP.Final_Diagnosis + ' 2.) ' +
> dbo.TempERCP.Final_Diagnosis2 + ' 3.) ' + dbo.TempERCP.Final_Diagnosis3
as
> [Final Diagnosis]
> thanks
> gv
>|||First the answer to your question:
Use isnull (assuming the first one can't be null...):
select '1.) ' + dbo.TempERCP.Final_Diagnosis, +
isnull(' 2.) ' + dbo.TempERCP.Final_Diagnosis2, '') +
isnull(' 3.) ' + dbo.TempERCP.Final_Diagnosis3, '') as [Final Diagnosis]
Then a quick spell of preachiness. Columns that end in numbers are
generally a sign of a bad idea (not to mention I don't want to go to a
doctor that gives me three different final_diagnoses :) Putting these in a
different table would make dealing with them in SQL far easier, and doing
this formatting in the client would be easier still.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"gv" <viatorg@.musc.edu> wrote in message
news:eC28HedIGHA.1088@.tk2msftngp13.phx.gbl...
> Hi all,
> The following is in Select list, it returns null, how do I account if
> there is a null in there or not
> when writting this?
> '1.) ' + dbo.TempERCP.Final_Diagnosis + ' 2.) ' +
> dbo.TempERCP.Final_Diagnosis2 + ' 3.) ' + dbo.TempERCP.Final_Diagnosis3
> as [Final Diagnosis]
> thanks
> gv
>|||SELECT
COALESCE(
'1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis2 + ' 3.) ' +
Final_Diagnosis3,
'1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis2,
'1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis3,
'1.) ' + Final_Diagnosis,
'1.) ' + Final_Diagnosis2,
'1.) ' + Final_Diagnosis2 + ' 2.) ' + Final_Diagnosis3,
'1.) ' + Final_Diagnosis3,
'No Diagnosis for Patient')
AS
[Final Diagnosis]
That being said, I would strongly suggest considering redesigning your db so
that this information is not stored in repeating columns.
(If Celko sees this, be prepared for an onslaught!)
"gv" wrote:

> Hi all,
> The following is in Select list, it returns null, how do I account if ther
e
> is a null in there or not
> when writting this?
> '1.) ' + dbo.TempERCP.Final_Diagnosis + ' 2.) ' +
> dbo.TempERCP.Final_Diagnosis2 + ' 3.) ' + dbo.TempERCP.Final_Diagnosis3
as
> [Final Diagnosis]
> thanks
> gv
>
>|||thanks
gv
"Mark Williams" <MarkWilliams@.discussions.microsoft.com> wrote in message
news:D265A10D-4E09-438E-BCF4-25CD9AB8276F@.microsoft.com...
> SELECT
> COALESCE(
> '1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis2 + ' 3.) ' +
> Final_Diagnosis3,
> '1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis2,
> '1.) ' + Final_Diagnosis + ' 2.) ' + Final_Diagnosis3,
> '1.) ' + Final_Diagnosis,
> '1.) ' + Final_Diagnosis2,
> '1.) ' + Final_Diagnosis2 + ' 2.) ' + Final_Diagnosis3,
> '1.) ' + Final_Diagnosis3,
> 'No Diagnosis for Patient')
> AS
> [Final Diagnosis]
> That being said, I would strongly suggest considering redesigning your db
> so
> that this information is not stored in repeating columns.
> (If Celko sees this, be prepared for an onslaught!)
> --
> "gv" wrote:
>|||thks
gv
"Trey Walpole" <treypole@.newsgroups.nospam> wrote in message
news:eP1G5odIGHA.2064@.TK2MSFTNGP09.phx.gbl...
> see isnull() or coalesce() in BOL
>
> gv wrote:|||I agree with you on the column and table structures, long story and was not
created by
me.
thanks
gv
"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:OpGzcqdIGHA.216@.TK2MSFTNGP15.phx.gbl...
> First the answer to your question:
> Use isnull (assuming the first one can't be null...):
> select '1.) ' + dbo.TempERCP.Final_Diagnosis, +
> isnull(' 2.) ' + dbo.TempERCP.Final_Diagnosis2, '') +
> isnull(' 3.) ' + dbo.TempERCP.Final_Diagnosis3, '') as [Final
> Diagnosis]
> Then a quick spell of preachiness. Columns that end in numbers are
> generally a sign of a bad idea (not to mention I don't want to go to a
> doctor that gives me three different final_diagnoses :) Putting these in
> a different table would make dealing with them in SQL far easier, and
> doing this formatting in the client would be easier still.
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
> "Arguments are to be avoided: they are always vulgar and often
> convincing."
> (Oscar Wilde)
> "gv" <viatorg@.musc.edu> wrote in message
> news:eC28HedIGHA.1088@.tk2msftngp13.phx.gbl...
>|||Been there done that. I just try never to give advice like this without
making sure :)
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"gv" <viatorg@.musc.edu> wrote in message
news:uu83f0dIGHA.3492@.TK2MSFTNGP09.phx.gbl...
>I agree with you on the column and table structures, long story and was not
>created by
> me.
> thanks
> gv
>
> "Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
> news:OpGzcqdIGHA.216@.TK2MSFTNGP15.phx.gbl...
>

Thursday, February 16, 2012

Checking for Nulls in String

Hi all,

I have the following SQL string;

SELECT Title +' '+ FirstName +' '+ MiddleName +' '+ LastName AS PersonsName FROM MyData...Contacts;

I want to build the persons name into a single string, but all the fields are not always filled in, can anyone tell me the best way to build this so I don't have extra blank spaces when I don't need them?

Basically I need to check if the field has a value, if it does include it, if not leave it out.

Thanks


You have two option use COALESCE or ISNUL in you code, try the link below for details. Hope this helps.

http://hkmicc.wordpress.com/2007/05/25/string-concatenation-in-sql-server/

|||

There are several different ways to handle this, depending upon whether or not you are storing NULL values or empty strings.

Here is a solution if you are storing NULL values:

Code Snippet


SET NOCOUNT ON


DECLARE @.MyContacts table
( RowID int IDENTITY,
Title varchar(10),
FirstName varchar(20),
MiddleName varchar(20),
LastName varchar(20)
)


INSERT INTO @.MyContacts VALUES ( 'Dr', 'William', 'R', 'Smith' )
INSERT INTO @.MyContacts VALUES ( NULL, 'Bob', NULL, 'Jones' )
INSERT INTO @.MyContacts VALUES ( NULL, 'Mary', 'Anne', 'Williams' )
INSERT INTO @.MyContacts VALUES ( 'Judge', NULL, NULL, 'Wapner' )
INSERT INTO @.MyContacts VALUES ( 'Major', 'Minor', NULL, 'Major' )
INSERT INTO @.MyContacts VALUES ( NULL, 'R', 'P', 'Adams' )


SELECT
PersonsName = isnull((Title + ' '), '' ) +
isnull((FirstName + ' '), '') +
isnull((MiddleName + ' '), '') +
isnull((LastName), '' )
FROM @.MyContacts

PersonsName
-
Dr William R Smith
Bob Jones
Mary Anne Williams
Judge Wapner
Major Minor Major
R P Adams

If you are storing empty strings, you could add a nullif() function around each Field, e.g., isnull((nullif(Title,'') + ' '), '').

|||

Thanks for the replies.

Arnie, your solutions works perfectly, thanks for taking the time.

Regards

Melt

checking for null statement in sql

Hi Everyone,

I have a query

select name, address, city from table1

I want to append address +'-' + city in this query . I want to show hyphen only if both address and city are not null. If name is null then I don't want to show hyphen. How can I get around this problem.

Any help will be appreciated.

Thanks,

Vinki

It depends on how you're displaying it -

Also - will there be mulitple records returned?

You could keep the query the way it is - but, based on what is returned, with each row, write a function to do that for you, display-wise only.

|||If you want to do it within your query then look at the CASE statement -see here for details. The idea is you do something like:

SELECT Name, CASE Address + City WHEN NULL THEN NULL ELSE Address + ' - ' + City END FROM Table1

You'll need to put in more conditions, but that's the basic syntax.

Another alternative is to look at user-defined functions.|||I'd suggest this:

SELECT Name, Address + ISNULL(Address + City,'','-') + City FROM Table1

I don't understand this part of your requirement, though:

vinki wrote:


If name is null then I don't want to show hyphen