Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Thursday, March 29, 2012

Configure Auto-start option in SQL agent

Is there a way I can set the Auto-start option in SQL Server agent to
true from my program. This can be done through a DOS command, SQL
statement, or anything else I can execute through my program. I know
how to start the agent from my software, I just don't know how to set
it to auto-start.
Any suggestions?You could use the sc.exe command prompt utility (sc config). Check
http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechnol/windowsserver2003/proddocs/entserver/sc.asp.
--
Dejan Sarka, SQL Server MVP
FAQ from Neil & others at: http://www.sqlserverfaq.com
Please reply only to the newsgroups.
PASS - the definitive, global community
for SQL Server professionals - http://www.sqlpass.org
"Ray Lavelle" <bostonpartykid@.yahoo.com> wrote in message
news:d8653140.0309061823.6f44952a@.posting.google.com...
> Is there a way I can set the Auto-start option in SQL Server agent to
> true from my program. This can be done through a DOS command, SQL
> statement, or anything else I can execute through my program. I know
> how to start the agent from my software, I just don't know how to set
> it to auto-start.
> Any suggestions?|||Other options include using Service Control Manager e.g.
scm -Silent 1 -Action 7 -Service SQLServerAgent -SvcStartType 2
or from TSQL
exec xp_cmdshell 'scm -Silent 1 -Action 7 -Service
SQLServerAgent -SvcStartType 2'
You could also use SQLDMO from VBScript
--
HTH
Jasper Smith (SQL Server MVP)
I support PASS - the definitive, global
community for SQL Server professionals -
http://www.sqlpass.org
"Ray Lavelle" <bostonpartykid@.yahoo.com> wrote in message
news:d8653140.0309061823.6f44952a@.posting.google.com...
Is there a way I can set the Auto-start option in SQL Server agent to
true from my program. This can be done through a DOS command, SQL
statement, or anything else I can execute through my program. I know
how to start the agent from my software, I just don't know how to set
it to auto-start.
Any suggestions?|||That worked great, thanks!!!!
"Jasper Smith" <jasper_smith9@.hotmail.com> wrote in message news:<uRJvexUdDHA.2508@.tk2msftngp13.phx.gbl>...
> Other options include using Service Control Manager e.g.
> scm -Silent 1 -Action 7 -Service SQLServerAgent -SvcStartType 2
> or from TSQL
> exec xp_cmdshell 'scm -Silent 1 -Action 7 -Service
> SQLServerAgent -SvcStartType 2'
> You could also use SQLDMO from VBScript
> --
> HTH
> Jasper Smith (SQL Server MVP)
> I support PASS - the definitive, global
> community for SQL Server professionals -
> http://www.sqlpass.org
> "Ray Lavelle" <bostonpartykid@.yahoo.com> wrote in message
> news:d8653140.0309061823.6f44952a@.posting.google.com...
> Is there a way I can set the Auto-start option in SQL Server agent to
> true from my program. This can be done through a DOS command, SQL
> statement, or anything else I can execute through my program. I know
> how to start the agent from my software, I just don't know how to set
> it to auto-start.
> Any suggestions?

Sunday, March 25, 2012

Config SQL Server properties to use Fixed Memory

Can I use an SQL statement to configure an SQL server to use Fixed
Memory size as opposed to the default Dynamic ? I don't want to use
the GUI.
Thanks
Sid.Hello,
You will have to use SP_CONFIGURE system storedprocedure.
Below example will tell SQL Server to use 4 GB of RAM.
SP_CONFIGURE 'max server memory', 4096
RECONFIGURE
GO
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172763475.361495.109810@.p10g2000cwp.googlegroups.com...
> Can I use an SQL statement to configure an SQL server to use Fixed
> Memory size as opposed to the default Dynamic ? I don't want to use
> the GUI.
> Thanks
> Sid.
>|||I suppose you could use
sp_configure with the following arguments:
max server memory (MB)
min server memory (MB)
and then reconfigure. Any particular reason you want to turn off the dynamic
memory management?
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com|||On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> I suppose you could use
> sp_configure with the following arguments:
> max server memory (MB)
> min server memory (MB)
> and then reconfigure. Any particular reason you want to turn off the dynam
ic
> memory management?
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
We are configuring the memory of a server that runs one of our vendors
applications. If we don't set the memory constraints, the application
will eventually use all the memory and seize the server. Right now we
set the memory as fixed and set its size at half the system memory.
Is there any way to specify the fixed memory with a variable ?
( 50% )
Thanks
Sid.|||No, You will have set the memory in MB based on the physical memory
availability.
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172766417.255720.121360@.30g2000cwc.googlegroups.com...
> On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> We are configuring the memory of a server that runs one of our vendors
> applications. If we don't set the memory constraints, the application
> will eventually use all the memory and seize the server. Right now we
> set the memory as fixed and set its size at half the system memory.
> Is there any way to specify the fixed memory with a variable ?
> ( 50% )
> Thanks
> Sid.
>
>
>|||Something like this should do it:
declare @.x int
select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
from sys.dm_os_sys_info
exec sp_configure 'max server memory (MB)', @.x
reconfigure
exec sp_configure 'min server memory (MB)', @.x
reconfigure
Note that I'd thoroughly test this sort of code first - I haven't thoroughly
tested sys.dm_os_sys_info on different environments yet.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com|||On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Something like this should do it:
> declare @.x int
> select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
> from sys.dm_os_sys_info
> exec sp_configure 'max server memory (MB)', @.x
> reconfigure
> exec sp_configure 'min server memory (MB)', @.x
> reconfigure
> Note that I'd thoroughly test this sort of code first - I haven't thorough
ly
> tested sys.dm_os_sys_info on different environments yet.
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
Thanks for the example.
Question: Why are you not setting the 'fixed' as opposed to the Max
and Min ?|||> Question: Why are you not setting the 'fixed' as opposed to the Max
> and Min ?
There is no such setting. There's a max and a min. The GUI fools us into bel
ieving that there's a
fixed, but it only sets max and min to the same value.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"sid" <sidwelle@.alexian.net> wrote in message
news:1172772610.650684.3930@.v33g2000cwv.googlegroups.com...
> On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Thanks for the example.
> Question: Why are you not setting the 'fixed' as opposed to the Max
> and Min ?
>|||On Mar 1, 12:54 pm, "Tibor Karaszi"
<tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
> There is no such setting. There's a max and a min. The GUI fools us into b
elieving that there's a
> fixed, but it only sets max and min to the same value.
> --
> Tibor Karaszi, SQL Server MVPhttp://www.karaszi.com/sqlserver/default.asph
ttp://sqlblog.com/blogs/tibor_karaszi
> "sid" <sidwe...@.alexian.net> wrote in message
> news:1172772610.650684.3930@.v33g2000cwv.googlegroups.com...
>
>
>
>
>
>
>
>
>
>
> - Show quoted text -
When I try to execute I get "Incorrect syntax near the keywork 'as' "
Thanks
Sid.|||Sorry - it's from an earlier query. Please remove "as
Half_physical_memory_in_MB" and run it.
Paul Ibison

Config SQL Server properties to use Fixed Memory

Can I use an SQL statement to configure an SQL server to use Fixed
Memory size as opposed to the default Dynamic ? I don't want to use
the GUI.
Thanks
Sid.
Hello,
You will have to use SP_CONFIGURE system storedprocedure.
Below example will tell SQL Server to use 4 GB of RAM.
SP_CONFIGURE 'max server memory', 4096
RECONFIGURE
GO
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172763475.361495.109810@.p10g2000cwp.googlegr oups.com...
> Can I use an SQL statement to configure an SQL server to use Fixed
> Memory size as opposed to the default Dynamic ? I don't want to use
> the GUI.
> Thanks
> Sid.
>
|||I suppose you could use
sp_configure with the following arguments:
max server memory (MB)
min server memory (MB)
and then reconfigure. Any particular reason you want to turn off the dynamic
memory management?
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com
|||On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> I suppose you could use
> sp_configure with the following arguments:
> max server memory (MB)
> min server memory (MB)
> and then reconfigure. Any particular reason you want to turn off the dynamic
> memory management?
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
We are configuring the memory of a server that runs one of our vendors
applications. If we don't set the memory constraints, the application
will eventually use all the memory and seize the server. Right now we
set the memory as fixed and set its size at half the system memory.
Is there any way to specify the fixed memory with a variable ?
( 50% )
Thanks
Sid.
|||No, You will have set the memory in MB based on the physical memory
availability.
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172766417.255720.121360@.30g2000cwc.googlegro ups.com...
> On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> We are configuring the memory of a server that runs one of our vendors
> applications. If we don't set the memory constraints, the application
> will eventually use all the memory and seize the server. Right now we
> set the memory as fixed and set its size at half the system memory.
> Is there any way to specify the fixed memory with a variable ?
> ( 50% )
> Thanks
> Sid.
>
>
>
|||Something like this should do it:
declare @.x int
select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
from sys.dm_os_sys_info
exec sp_configure 'max server memory (MB)', @.x
reconfigure
exec sp_configure 'min server memory (MB)', @.x
reconfigure
Note that I'd thoroughly test this sort of code first - I haven't thoroughly
tested sys.dm_os_sys_info on different environments yet.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com
|||On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Something like this should do it:
> declare @.x int
> select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
> from sys.dm_os_sys_info
> exec sp_configure 'max server memory (MB)', @.x
> reconfigure
> exec sp_configure 'min server memory (MB)', @.x
> reconfigure
> Note that I'd thoroughly test this sort of code first - I haven't thoroughly
> tested sys.dm_os_sys_info on different environments yet.
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
Thanks for the example.
Question: Why are you not setting the 'fixed' as opposed to the Max
and Min ?
|||On Mar 1, 12:54 pm, "Tibor Karaszi"
<tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
> There is no such setting. There's a max and a min. The GUI fools us into believing that there's a
> fixed, but it only sets max and min to the same value.
> --
> Tibor Karaszi, SQL Server MVPhttp://www.karaszi.com/sqlserver/default.asphttp://sqlblog.com/blogs/tibor_karaszi
> "sid" <sidwe...@.alexian.net> wrote in message
> news:1172772610.650684.3930@.v33g2000cwv.googlegrou ps.com...
>
>
>
>
>
>
> - Show quoted text -
When I try to execute I get "Incorrect syntax near the keywork 'as' "
Thanks
Sid.
|||Sorry - it's from an earlier query. Please remove "as
Half_physical_memory_in_MB" and run it.
Paul Ibison
|||On Mar 1, 4:59 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Sorry - it's from an earlier query. Please remove "as
> Half_physical_memory_in_MB" and run it.
> Paul Ibison
I had already done that, but I still get " Invalid object name
'sys.dm_os_sys_info' "
I am using SQL 2k
Thanks
Sid.

Config SQL Server properties to use Fixed Memory

Can I use an SQL statement to configure an SQL server to use Fixed
Memory size as opposed to the default Dynamic ? I don't want to use
the GUI.
Thanks
Sid.Hello,
You will have to use SP_CONFIGURE system storedprocedure.
Below example will tell SQL Server to use 4 GB of RAM.
SP_CONFIGURE 'max server memory', 4096
RECONFIGURE
GO
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172763475.361495.109810@.p10g2000cwp.googlegroups.com...
> Can I use an SQL statement to configure an SQL server to use Fixed
> Memory size as opposed to the default Dynamic ? I don't want to use
> the GUI.
> Thanks
> Sid.
>|||I suppose you could use
sp_configure with the following arguments:
max server memory (MB)
min server memory (MB)
and then reconfigure. Any particular reason you want to turn off the dynamic
memory management?
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com|||On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> I suppose you could use
> sp_configure with the following arguments:
> max server memory (MB)
> min server memory (MB)
> and then reconfigure. Any particular reason you want to turn off the dynamic
> memory management?
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
We are configuring the memory of a server that runs one of our vendors
applications. If we don't set the memory constraints, the application
will eventually use all the memory and seize the server. Right now we
set the memory as fixed and set its size at half the system memory.
Is there any way to specify the fixed memory with a variable ?
( 50% )
Thanks
Sid.|||No, You will have set the memory in MB based on the physical memory
availability.
Thanks
Hari
"sid" <sidwelle@.alexian.net> wrote in message
news:1172766417.255720.121360@.30g2000cwc.googlegroups.com...
> On Mar 1, 10:13 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
>> I suppose you could use
>> sp_configure with the following arguments:
>> max server memory (MB)
>> min server memory (MB)
>> and then reconfigure. Any particular reason you want to turn off the
>> dynamic
>> memory management?
>> Cheers,
>> Paul Ibison SQL Server MVP,www.replicationanswers.com
> We are configuring the memory of a server that runs one of our vendors
> applications. If we don't set the memory constraints, the application
> will eventually use all the memory and seize the server. Right now we
> set the memory as fixed and set its size at half the system memory.
> Is there any way to specify the fixed memory with a variable ?
> ( 50% )
> Thanks
> Sid.
>
>
>|||Something like this should do it:
declare @.x int
select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
from sys.dm_os_sys_info
exec sp_configure 'max server memory (MB)', @.x
reconfigure
exec sp_configure 'min server memory (MB)', @.x
reconfigure
Note that I'd thoroughly test this sort of code first - I haven't thoroughly
tested sys.dm_os_sys_info on different environments yet.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com|||On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Something like this should do it:
> declare @.x int
> select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
> from sys.dm_os_sys_info
> exec sp_configure 'max server memory (MB)', @.x
> reconfigure
> exec sp_configure 'min server memory (MB)', @.x
> reconfigure
> Note that I'd thoroughly test this sort of code first - I haven't thoroughly
> tested sys.dm_os_sys_info on different environments yet.
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
Thanks for the example.
Question: Why are you not setting the 'fixed' as opposed to the Max
and Min ?|||> Question: Why are you not setting the 'fixed' as opposed to the Max
> and Min ?
There is no such setting. There's a max and a min. The GUI fools us into believing that there's a
fixed, but it only sets max and min to the same value.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"sid" <sidwelle@.alexian.net> wrote in message
news:1172772610.650684.3930@.v33g2000cwv.googlegroups.com...
> On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
>> Something like this should do it:
>> declare @.x int
>> select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
>> from sys.dm_os_sys_info
>> exec sp_configure 'max server memory (MB)', @.x
>> reconfigure
>> exec sp_configure 'min server memory (MB)', @.x
>> reconfigure
>> Note that I'd thoroughly test this sort of code first - I haven't thoroughly
>> tested sys.dm_os_sys_info on different environments yet.
>> Cheers,
>> Paul Ibison SQL Server MVP,www.replicationanswers.com
> Thanks for the example.
> Question: Why are you not setting the 'fixed' as opposed to the Max
> and Min ?
>|||On Mar 1, 12:54 pm, "Tibor Karaszi"
<tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
> > Question: Why are you not setting the 'fixed' as opposed to the Max
> > and Min ?
> There is no such setting. There's a max and a min. The GUI fools us into believing that there's a
> fixed, but it only sets max and min to the same value.
> --
> Tibor Karaszi, SQL Server MVPhttp://www.karaszi.com/sqlserver/default.asphttp://sqlblog.com/blogs/tibor_karaszi
> "sid" <sidwe...@.alexian.net> wrote in message
> news:1172772610.650684.3930@.v33g2000cwv.googlegroups.com...
>
> > On Mar 1, 11:38 am, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> >> Something like this should do it:
> >> declare @.x int
> >> select @.x = physical_memory_in_bytes / 500.0 as Half_physical_memory_in_MB
> >> from sys.dm_os_sys_info
> >> exec sp_configure 'max server memory (MB)', @.x
> >> reconfigure
> >> exec sp_configure 'min server memory (MB)', @.x
> >> reconfigure
> >> Note that I'd thoroughly test this sort of code first - I haven't thoroughly
> >> tested sys.dm_os_sys_info on different environments yet.
> >> Cheers,
> >> Paul Ibison SQL Server MVP,www.replicationanswers.com
> > Thanks for the example.
> > Question: Why are you not setting the 'fixed' as opposed to the Max
> > and Min ... Hide quoted text -
> - Show quoted text -
When I try to execute I get "Incorrect syntax near the keywork 'as' "
Thanks
Sid.|||Sorry - it's from an earlier query. Please remove "as
Half_physical_memory_in_MB" and run it.
Paul Ibison|||On Mar 1, 4:59 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> Sorry - it's from an earlier query. Please remove "as
> Half_physical_memory_in_MB" and run it.
> Paul Ibison
I had already done that, but I still get " Invalid object name
'sys.dm_os_sys_info' "
I am using SQL 2k
Thanks
Sid.|||For SQL2K, check out below:
sysconfigures
syscurconfigs
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"sid" <sidwelle@.alexian.net> wrote in message
news:1172851212.691239.101580@.s48g2000cws.googlegroups.com...
> On Mar 1, 4:59 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
>> Sorry - it's from an earlier query. Please remove "as
>> Half_physical_memory_in_MB" and run it.
>> Paul Ibison
> I had already done that, but I still get " Invalid object name
> 'sys.dm_os_sys_info' "
> I am using SQL 2k
> Thanks
> Sid.
>|||On Mar 2, 10:37 am, "Tibor Karaszi"
<tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
> For SQL2K, check out below:
> sysconfigures
> syscurconfigs
> --
> Tibor Karaszi, SQL Server MVPhttp://www.karaszi.com/sqlserver/default.asphttp://sqlblog.com/blogs/tibor_karaszi
> "sid" <sidwe...@.alexian.net> wrote in message
> news:1172851212.691239.101580@.s48g2000cws.googlegroups.com...
>
> > On Mar 1, 4:59 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> >> Sorry - it's from an earlier query. Please remove "as
> >> Half_physical_memory_in_MB" and run it.
> >> Paul Ibison
> > I had already done that, but I still get " Invalid object name
> > 'sys.dm_os_sys_info' "
> > I am using SQL 2k
> > Thanks
> > Sid.- Hide quoted text -
> - Show quoted text -
Nice to know those tables are there, but I didn't see a field for
system memory.
Sid.|||You mean row? Did you turn on "show advanced options"?
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"sid" <sidwelle@.alexian.net> wrote in message
news:1172865017.402571.254540@.8g2000cwh.googlegroups.com...
> On Mar 2, 10:37 am, "Tibor Karaszi"
> <tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
>> For SQL2K, check out below:
>> sysconfigures
>> syscurconfigs
>> --
>> Tibor Karaszi, SQL Server
>> MVPhttp://www.karaszi.com/sqlserver/default.asphttp://sqlblog.com/blogs/tibor_karaszi
>> "sid" <sidwe...@.alexian.net> wrote in message
>> news:1172851212.691239.101580@.s48g2000cws.googlegroups.com...
>>
>> > On Mar 1, 4:59 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
>> >> Sorry - it's from an earlier query. Please remove "as
>> >> Half_physical_memory_in_MB" and run it.
>> >> Paul Ibison
>> > I had already done that, but I still get " Invalid object name
>> > 'sys.dm_os_sys_info' "
>> > I am using SQL 2k
>> > Thanks
>> > Sid.- Hide quoted text -
>> - Show quoted text -
> Nice to know those tables are there, but I didn't see a field for
> system memory.
> Sid.
>|||As far as I can tell from digging through the system tables on SQL Server
2000 this info wasn't available to TSQL directly. You could read it in a COM
object and reference that in a stored proc using the sp_oa.. procedures.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com|||On Mar 6, 4:32 pm, "Paul Ibison" <Paul.Ibi...@.Pygmalion.Com> wrote:
> As far as I can tell from digging through the system tables on SQL Server
> 2000 this info wasn't available to TSQL directly. You could read it in a COM
> object and reference that in a stored proc using the sp_oa.. procedures.
> Cheers,
> Paul Ibison SQL Server MVP,www.replicationanswers.com
Thanks Paul, thats about what I had figured.
I atleast got what I needed out of it.
Sid.

Tuesday, March 20, 2012

conditionally executing sql statement

I need to write .sql file in a dynamic way.
inside the file i need to decide at run time (of the sql script) whether or
not to run a SQL statement that I don't know it's content while dynamically
creating the sql script, this sql statement might include a GO statement
what makes a problem putting it inside an if begin end block.
for example
in my script a runtime check
select @.runStatement = configVal from database at script runtime execution
if @.runStatement =1
begin
-- here comes an unknown sql statement at the time of creating the sql
script that might include a GO command which will break the syntax of the
entire block
-- go <- this here makes a TSQL error for the end command since it
breaks the begin / end block.
end
can someone recomend of an approach for how to solve this?
execute sql is not an option here since the internal SQL statement might be
larget then 4000 nvarchar characters and I can not declarae a @.ntext local
variable
TIA.>> inside the file i need to decide at run time (of the sql script) whether
Under normal circumstances, this is a poor way to write SQL code. The kludgy
workaround is to assign the SQL statement to a variable, replace the tokens
that are not needed and use EXEC or sp_ExecuteSQL to execute it.
The right way can be suggested only if you can explain the overall
situation. Why do you have to resort to such complex approach? Is there a
3rd party tool involved?
Anith|||martin (news.microsoft.com) writes:
> I need to write .sql file in a dynamic way.
> inside the file i need to decide at run time (of the sql script) whether
> or not to run a SQL statement that I don't know it's content while
> dynamically creating the sql script, this sql statement might include a
> GO statement what makes a problem putting it inside an if begin end
> block.
> for example
> in my script a runtime check
> select @.runStatement = configVal from database at script runtime execution
> if @.runStatement =1
> begin
> -- here comes an unknown sql statement at the time of creating the
> sql script that might include a GO command which will break the syntax
> of the entire block
> -- go <- this here makes a TSQL error for the end command since it
> breaks the begin / end block.
> end
>
> can someone recomend of an approach for how to solve this?
> execute sql is not an option here since the internal SQL statement might
> be larget then 4000 nvarchar characters and I can not declarae a @.ntext
> local variable
Are you on SQL 2000 or SQL 2005?
If you are on SQL 2000, I would srtongly recommend that you run the
control loop from a client. It could be very difficult to sort out
from SQL only. It could be a little easier on SQL 2005, since there
you can work with nvarchar(MAX) and you could do the batch splitting
in CLR code.
I echoes Aniths suggestion that you could be better served by telling
us the full story. This could give you better suggestions.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||it should support database modifications / upgrades.
the commands are not known at the time of designing the tool that will
execute the statements.
i understand that running each script from a client tool like a VB.NET app
is a good option but is it not possible to run it from sql script file using
some goto label....?
"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:eedlU0VaGHA.1020@.TK2MSFTNGP02.phx.gbl...
> Under normal circumstances, this is a poor way to write SQL code. The
> kludgy workaround is to assign the SQL statement to a variable, replace
> the tokens that are not needed and use EXEC or sp_ExecuteSQL to execute
> it.
>
> The right way can be suggested only if you can explain the overall
> situation. Why do you have to resort to such complex approach? Is there a
> 3rd party tool involved?
> --
> Anith
>|||martin (news.microsoft.com) writes:
> it should support database modifications / upgrades.
> the commands are not known at the time of designing the tool that will
> execute the statements.
> i understand that running each script from a client tool like a VB.NET
> app is a good option but is it not possible to run it from sql script
> file using some goto label....?
Possible and possible. With severe kludges maybe. And it depends on the SQL
Server version.
If the purpose of the tool is run scripts for database changes, I strongly
recommend using a control part in a client language.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspxsqlsql

Conditionalize field values based on other field values

Here's a portion of the current statement.

UPDATE EngagementAuditAreas

SET numDeterminationLevelTypeId = parent.numDeterminationLevelTypeId,

numInherentRiskID = parent.numInherentRiskID,

numControlRiskID = parent.numControlRiskID,

numCombinedRiskID = parent.numCombinedRiskID,

numApproachTypeId = parent.numApproachTypeId,

bInherentRiskIsAffirmed = 0,

bControlRiskIsAffirmed = 0,

bCombinedRiskIsAffirmed = 0,

bApproachTypeIsAffirmed = 0,

bCommentsIsAffirmed = 0

FROM EngagementAuditAreas WITH(NOLOCK) ...

And what I need is to conditionalize the values of the "IsAffirmed" fields by looking at their corresponding "num" fields. Something like this (which doesn't work).

UPDATE EngagementAuditAreas

SET numDeterminationLevelTypeId = parent.numDeterminationLevelTypeId,

numInherentRiskID = parent.numInherentRiskID,

numControlRiskID = parent.numControlRiskID,

numCombinedRiskID = parent.numCombinedRiskID,

numApproachTypeId = parent.numApproachTypeId,

bInherentRiskIsAffirmed = (numInherentRiskID IS NULL),

bControlRiskIsAffirmed = (numControlRiskID IS NULL),

bCombinedRiskIsAffirmed = (numCombinedRiskID IS NULL),

bApproachTypeIsAffirmed = (numApproachTypeID IS NULL),

bCommentsIsAffirmed = (parent.txtComments IS NULL)

FROM EngagementAuditAreas WITH(NOLOCK)

Thanks.

Here is a small example of how you might accomplish your task.

Code Snippet


DECLARE @.MyTable table
( RowID int IDENTITY,
Affirmed char(4),
Num int
)


SET NOCOUNT ON


INSERT INTO @.MyTable VALUES ( NULL, 1 )
INSERT INTO @.MyTable VALUES ( NULL, 0 )
INSERT INTO @.MyTable VALUES ( NULL, NULL )


UPDATE @.MyTable
SET Affirmed = CASE Num
WHEN 0 THEN 'Yes'
WHEN 1 THEN 'No'
ELSE 'n/a'
END


SELECT *
FROM @.MyTable


RowID Affirmed Num
-- -- --
1 No 1
2 Yes 0
3 n/a NULL


However, it is usually NOT a good idea to have two columns that contain the same information (even if in two forms). You can easily 'transform' the values in the select queries using the same CASE structure as above.

Conditional WHERE statement?

Hi all,

I have one for all the blackbelters out there: is there a way i can
make a stored procedure where i can control the where statement with
variables? I have to do some complex transformations to get compose a
fact table for MSAS and there a a lot of similarities between the
queries and a few differences because of different account methods
etc. (booking in starting date, booking stuff on order entry dates
etc) I want to put a combination of different rules in different
members of dimensions.

An example of what i mean:

CREATE STORED PROCEDURE dbo.FILLFACT (@.PAR1, @.PAR2)
AS
INSERT INTO FactTable (blah blah)

SELECT
IF @.PAR1 = 'OrderDate'
SourceView.Orderdate
ELSE
SourceView.StartDate
,
etc etc...

FROM
SourceView

WHERE
IF @.PAR2 = 'WholeTable'
1=1
IF @.PAR2 = 'Incomplete'
EndDate IS NULL OR EXIST (SELECT * FROM Exceptions WHERE
..., etc)

This way i could fill my fact table with

EXEC dbo.FillFact 'beginDate','Wholetable'
EXEC dbo.FillFact 'begindate', 'Rulebook1'
EXEC dbo.FillFact 'BeginDate', 'Exceptions'
etcetera.

This is not an actual SQL script i use, just an example of what i'm
talking about. Or maybe i could pass the where statement entirley as a
variable? But i can't use SET @.PAR1 = 'EndDate IS NULL' and then use
WHERE @.PAR1 can I?

I hope i'm making sense. Does anyone know if this is possible? Right
now i have a procedure that is composed of a dozen of sql scripts that
are mostly the same, but i have to copy it for every combination of
situations and then, of course, new stuff has to be added on 12
different places. Again and again.

Any thoughts?

TIA,

Gert-Jan van der Kamp[posted and mailed, please reply in news]

G.J. v.d. Kamp (gjvdkamp@.hotmail.com) writes:
> I have one for all the blackbelters out there: is there a way i can
> make a stored procedure where i can control the where statement with
> variables? I have to do some complex transformations to get compose a
> fact table for MSAS and there a a lot of similarities between the
> queries and a few differences because of different account methods
> etc. (booking in starting date, booking stuff on order entry dates
> etc) I want to put a combination of different rules in different
> members of dimensions.

I believe that my article on dynamic search condition should give
you some ideas to work from. Look at
http://www.sommarskog.se/dyn-search.html.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||That's exectly what i mean, thanx!

Erland Sommarskog <esquel@.sommarskog.se> wrote in message news:<Xns95F2F1FFAE1DEYazorman@.127.0.0.1>...
> [posted and mailed, please reply in news]
> G.J. v.d. Kamp (gjvdkamp@.hotmail.com) writes:
> > I have one for all the blackbelters out there: is there a way i can
> > make a stored procedure where i can control the where statement with
> > variables? I have to do some complex transformations to get compose a
> > fact table for MSAS and there a a lot of similarities between the
> > queries and a few differences because of different account methods
> > etc. (booking in starting date, booking stuff on order entry dates
> > etc) I want to put a combination of different rules in different
> > members of dimensions.
> I believe that my article on dynamic search condition should give
> you some ideas to work from. Look at
> http://www.sommarskog.se/dyn-search.html.sqlsql

conditional where statement

I have a stored procedure that performs a search function with params:

@.username nvarchar(50)
@.country nvarchar(50)
and like 10 more.

A user may provide values for these params optionally.
So when the @.username var is left blank, there should be no filtering on the username field (every field should be selected regardless of the username)
Currently my statement is:

select username,country from myUsers where
username=@.username andcountry=@.country

With this statement when a user provides no value for username the username field selects on ''m which returns ofcourse nothing...

What can I do to solve this?

Thanks!

SELECTFROM YourTableWHERE (@.usernameISNULL OR UserName = @.username )AND (@.countryISNULL OR Country = @.country )
|||

Thanks, but in this case the username field would not be ignored.
If someone has filled in a username, say "peter", but the webvisitor would not want to search on any username, the statement would be:

SELECT
FROM YourTable
WHERE (@.usernameISNULL OR UserName = '' )

In this case the user with name "peter" would not be found. If a webvisitor does NOT provide a username, I want to return all rows regardless of the value in the username field...

Im just hoping I've explained myself clearly now :)

Thanks!

|||

use WHERE (UserName = COALESCE(@.UserName, UserName)) AND (Country = COALESCE(@.Country, Country)) AND etc.

COALESCE (or ISNULL if you prefer) will return the first value in the parameter list that is not null, so if you pass a NULL value for, say, @.UserName, that part of the WHERE clause will resolve to "WHERE UserName = UserName", which of course, is always true.

|||

Peter Smith:

If someone has filled in a username, say "peter", but the webvisitor would not want to search on any username

Can you explain what you mean by that? If there is a value in @.username, it will be searched against, else ignored. If there is a value provided and it does not exist in the table, obviously nothing will be returned. Incase the query doesnt work as expected, please provide some sample data, and sample scenarios and their expected outputs.

|||

Dinakar Nethi provided an excellent query for your issue. The key to implement is:

You need to set your input parameter to default NULL first.

@.UserName NVarchar(50) = NULL,

@.Country NVarchar(50) = NULL

|||

mmm, I see (now). I tested your query and it works :)
Thanks!

Conditional Where Clause w/ Case Statement Possible?

Greetings,

After many hours search many forums and many failed experiments, I figure it's time to turn to the experts.

I need to execute a query that changes the returned data based upon a parameter's value. In my example below, the lob field contains both text values and nulls.

SELECT uniqueID, lob, xdate

FROM mytable

WHERE

CASE WHEN @.myparam = 'ALL'

THEN

xdate >= '2007-09-01'

ELSE

xdate >= '2007-09-01' or

lob = @.myparm

END

I've experimented with various forms of the LIKE function, checking for null/not null and keep coming up blank.

I thought about using an IF statement and creating different versions of the entire statement, however, in real-life I need to do this with four fields using four parameters (one for each field). The permutations are a little too much.

Any ideas?

Rob

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In general, you can probably write:

WHERE

(@.p = 'Option1' AND (<option 1 condition>))

OR

(@.p = 'Option 2' AND (<option 2 condition>))

OR

...

Be careful where parentheses go, so AND and OR don't associate differently than you want.

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve Kass

Drew University

http://www.stevekass.com

|||

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

Code Snippet

If @.myparam = 'ALL'

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01'

ELSE

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01' or lob = @.myparm

|||

Steve Kass wrote:

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve - when @.myparm ='ALL', I want all of the records returned. The field (lob) does not actually contain the value 'ALL'.

I tried using a LIKE statement but found that nulls are not returned. For example, if @.myparm was populated with "%" and used in this query:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901') and

lob LIKE @.myparm

then all records with a value in lob are returned but those will a null are not. I need to inlcude the records with a null.

Rob

|||

Manivannan.D.Sekaran wrote:

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

The problem with using the IF statement is the number of permutation when I have four variables.

IF @.myparm1 = 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 1)

IF @.myparm1 <> 'ALL' and @.myparm2 = 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 2)

IF @.myparm1 <> 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 = 'ALL' and @.myparm4 <> 'ALL'

(query 3)

...

I think I'd wind up with 16 IF statements. While it should work, it would be very difficult to support.

Rob

|||

In your case the best solution is using the dynamic sql... Buliding the Where clause expression on the fly..

There are few limitations there while using the dynamic sql.. If you really need a best performance there is no compromise..

example,

Code Snippet

Declare @.SQL as Varchar(8000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = null;

Set @.Type ='U'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=''' + @.Name + ''''

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=''' + @.Type + ''''

Exec (@.SQL + @.Where)

Code Snippet

Declare @.SQL as NVarchar(4000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = NULL;

Set @.Type ='P'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=@.Name'

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=@.Type'

Set @.SQL = @.SQL + @.Where

Exec sp_executesql @.SQL, N'@.name varchar(100), @.type varchar(100)', @.name, @.type

|||Sorry, Rob. I misread your original intent, so let me try again. I think you want

1. If 'ALL' is passed: every row with xdate >= '20070901'
2. If 'ALL' is not passed: every row with xdate >= '20070901', as well as rows with lob = @.myparm, regardless of date.

First, a solution that assumes @.myparm is never NULL:

select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

Because you use NULL as a value for [lob], and you use @.myparm = NULL to select those rows, you can't rely on @.myparm = lob, which is not true when @.myparm and lob are both NULL. Unfortunately, you have to handle this separately, because T-SQL has no IS NOT DISTINCT FROM operator that means "are both equal or are both null". Whether you treat it as a third case or in the second case is up to you:

where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
) or (
@.myparm IS NULL
and
(lob IS NULL or xdate >= '20070901')
)

So this is like what a CASE statement would be. The structure is

where
you are in case 1 and the where clause for that case holds
or
you are in case 2 and the where clause for that case holds
...

The problem with NULL is because a CASE expression would allow an OTHERWISE clause to handle both @.myparm <> 'ALL' and @.myparm IS NULL at once.

Note that I wrote the date without hyphens. Unfortunately, if xdate is [datetime] or [smalldatetime], SQL Server installations that use European and many other non-US localizations will interpret the date as you wrote it to mean January 9, 2007. I doubt you ever want that, and you can avoid a surprise by using the format I provided, or the other "safe" format '2007-09-01T00:00:00' (the T is required).

SK

|||

Steve Kass wrote:


select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

SK

Steve,

Thank you very much. This did the trick. It's amazing what a few AND & OR statements can do with the correct paranthesis.

I'm actually using these queres in SSRS as a data source. It took a couple of edits to get SSRS to take the paranthesis correctly as it want to "fix" them for you.

Rob

Conditional Where Clause w/ Case Statement Possible?

Greetings,

After many hours search many forums and many failed experiments, I figure it's time to turn to the experts.

I need to execute a query that changes the returned data based upon a parameter's value. In my example below, the lob field contains both text values and nulls.

SELECT uniqueID, lob, xdate

FROM mytable

WHERE

CASE WHEN @.myparam = 'ALL'

THEN

xdate >= '2007-09-01'

ELSE

xdate >= '2007-09-01' or

lob = @.myparm

END

I've experimented with various forms of the LIKE function, checking for null/not null and keep coming up blank.

I thought about using an IF statement and creating different versions of the entire statement, however, in real-life I need to do this with four fields using four parameters (one for each field). The permutations are a little too much.

Any ideas?

Rob

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In general, you can probably write:

WHERE

(@.p = 'Option1' AND (<option 1 condition>))

OR

(@.p = 'Option 2' AND (<option 2 condition>))

OR

...

Be careful where parentheses go, so AND and OR don't associate differently than you want.

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve Kass

Drew University

http://www.stevekass.com

|||

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

Code Snippet

If @.myparam = 'ALL'

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01'

ELSE

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01' or lob = @.myparm

|||

Steve Kass wrote:

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve - when @.myparm ='ALL', I want all of the records returned. The field (lob) does not actually contain the value 'ALL'.

I tried using a LIKE statement but found that nulls are not returned. For example, if @.myparm was populated with "%" and used in this query:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901') and

lob LIKE @.myparm

then all records with a value in lob are returned but those will a null are not. I need to inlcude the records with a null.

Rob

|||

Manivannan.D.Sekaran wrote:

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

The problem with using the IF statement is the number of permutation when I have four variables.

IF @.myparm1 = 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 1)

IF @.myparm1 <> 'ALL' and @.myparm2 = 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 2)

IF @.myparm1 <> 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 = 'ALL' and @.myparm4 <> 'ALL'

(query 3)

...

I think I'd wind up with 16 IF statements. While it should work, it would be very difficult to support.

Rob

|||

In your case the best solution is using the dynamic sql... Buliding the Where clause expression on the fly..

There are few limitations there while using the dynamic sql.. If you really need a best performance there is no compromise..

example,

Code Snippet

Declare @.SQL as Varchar(8000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = null;

Set @.Type ='U'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=''' + @.Name + ''''

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=''' + @.Type + ''''

Exec (@.SQL + @.Where)

Code Snippet

Declare @.SQL as NVarchar(4000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = NULL;

Set @.Type ='P'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=@.Name'

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=@.Type'

Set @.SQL = @.SQL + @.Where

Exec sp_executesql @.SQL, N'@.name varchar(100), @.type varchar(100)', @.name, @.type

|||Sorry, Rob. I misread your original intent, so let me try again. I think you want

1. If 'ALL' is passed: every row with xdate >= '20070901'
2. If 'ALL' is not passed: every row with xdate >= '20070901', as well as rows with lob = @.myparm, regardless of date.

First, a solution that assumes @.myparm is never NULL:

select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

Because you use NULL as a value for [lob], and you use @.myparm = NULL to select those rows, you can't rely on @.myparm = lob, which is not true when @.myparm and lob are both NULL. Unfortunately, you have to handle this separately, because T-SQL has no IS NOT DISTINCT FROM operator that means "are both equal or are both null". Whether you treat it as a third case or in the second case is up to you:

where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
) or (
@.myparm IS NULL
and
(lob IS NULL or xdate >= '20070901')
)

So this is like what a CASE statement would be. The structure is

where
you are in case 1 and the where clause for that case holds
or
you are in case 2 and the where clause for that case holds
...

The problem with NULL is because a CASE expression would allow an OTHERWISE clause to handle both @.myparm <> 'ALL' and @.myparm IS NULL at once.

Note that I wrote the date without hyphens. Unfortunately, if xdate is [datetime] or [smalldatetime], SQL Server installations that use European and many other non-US localizations will interpret the date as you wrote it to mean January 9, 2007. I doubt you ever want that, and you can avoid a surprise by using the format I provided, or the other "safe" format '2007-09-01T00:00:00' (the T is required).

SK

|||

Steve Kass wrote:


select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

SK

Steve,

Thank you very much. This did the trick. It's amazing what a few AND & OR statements can do with the correct paranthesis.

I'm actually using these queres in SSRS as a data source. It took a couple of edits to get SSRS to take the paranthesis correctly as it want to "fix" them for you.

Rob

|||in t-sql you can have conditional where clauses
sample:

select * from mytable
where
mycol = case when @.i = 1 then 1 else 2 end

conditional WHERE clause

Hi
I have an SP with a few params and I wish to use one of the params in the
WHERE clause, to conditionaly set a WHERE statement, for example:
CREATE PROC sp_Test
@.ProductCode VARCHAR(5)
@.ProcessMonth INT = NULL,
@.ProcessYear INT = NULL
AS
SELECT Table.ID
FROM Table
WHERE
Table.PMonth = @.ProcessMonth
AND Table.PYear = @.ProcessYear
AND
IF @.ProductCode = 'ALL' THEN
BEGIN
Table.ProductCode = ('A','B','C' etc...all codes, need this to
be dynamic)
END
ELSE
BEGIN
Table.ProductCode = @.ProductCode
END
Hope this makes sense, I also don't know how to make the 'ALL' return all
records?
Kind Regards
RickyPWHERE
ProductCode = CASE @.ProductCode WHEN 'ALL' THEN ProductCode ELSE
@.ProductCode END
"ricky" <ricky@.ricky.com> wrote in message
news:efjM0q$UGHA.5248@.TK2MSFTNGP10.phx.gbl...
> Hi
> I have an SP with a few params and I wish to use one of the params in the
> WHERE clause, to conditionaly set a WHERE statement, for example:
> CREATE PROC sp_Test
> @.ProductCode VARCHAR(5)
> @.ProcessMonth INT = NULL,
> @.ProcessYear INT = NULL
> AS
> SELECT Table.ID
> FROM Table
> WHERE
> Table.PMonth = @.ProcessMonth
> AND Table.PYear = @.ProcessYear
> AND
> IF @.ProductCode = 'ALL' THEN
> BEGIN
> Table.ProductCode = ('A','B','C' etc...all codes, need this
> to
> be dynamic)
> END
> ELSE
> BEGIN
> Table.ProductCode = @.ProductCode
> END
> Hope this makes sense, I also don't know how to make the 'ALL' return all
> records?
> Kind Regards
> RickyP
>|||You may benefit by reading the article at:
http://www.sommarskog.se/dyn-search.html
Anith|||Hi
use northwind
go
create proc spproc
@.custid varchar(10)
as
select * from orders where CustomerID=
case when @.custid='all' then CustomerID else @.custid end
--usage
exec spproc 'vinet'
exec spproc 'all'
"ricky" <ricky@.ricky.com> wrote in message
news:efjM0q$UGHA.5248@.TK2MSFTNGP10.phx.gbl...
> Hi
> I have an SP with a few params and I wish to use one of the params in the
> WHERE clause, to conditionaly set a WHERE statement, for example:
> CREATE PROC sp_Test
> @.ProductCode VARCHAR(5)
> @.ProcessMonth INT = NULL,
> @.ProcessYear INT = NULL
> AS
> SELECT Table.ID
> FROM Table
> WHERE
> Table.PMonth = @.ProcessMonth
> AND Table.PYear = @.ProcessYear
> AND
> IF @.ProductCode = 'ALL' THEN
> BEGIN
> Table.ProductCode = ('A','B','C' etc...all codes, need this
> to
> be dynamic)
> END
> ELSE
> BEGIN
> Table.ProductCode = @.ProductCode
> END
> Hope this makes sense, I also don't know how to make the 'ALL' return all
> records?
> Kind Regards
> RickyP
>|||Hi Ricky,
How about :
SELECT * FROM MyTable
WHERE (Table.ProductCode = @.ProductCode OR @.ProductCode = 'ALL')
Should do what you're looking for. Personally, rather than 'ALL' I'd use
NULL to indicate that no filter should be applied (i.e. all product codes),
but this will work fine.
Cheers,
Alex
"ricky" <ricky@.ricky.com> wrote in message
news:efjM0q$UGHA.5248@.TK2MSFTNGP10.phx.gbl...
> Hi
> I have an SP with a few params and I wish to use one of the params in the
> WHERE clause, to conditionaly set a WHERE statement, for example:
> CREATE PROC sp_Test
> @.ProductCode VARCHAR(5)
> @.ProcessMonth INT = NULL,
> @.ProcessYear INT = NULL
> AS
> SELECT Table.ID
> FROM Table
> WHERE
> Table.PMonth = @.ProcessMonth
> AND Table.PYear = @.ProcessYear
> AND
> IF @.ProductCode = 'ALL' THEN
> BEGIN
> Table.ProductCode = ('A','B','C' etc...all codes, need this
> to
> be dynamic)
> END
> ELSE
> BEGIN
> Table.ProductCode = @.ProductCode
> END
> Hope this makes sense, I also don't know how to make the 'ALL' return all
> records?
> Kind Regards
> RickyP
>|||Great minds think alike - thanks guys for the postings, didn't know you
could do that.
Kind Regards
RickyP
"ricky" <ricky@.ricky.com> wrote in message
news:efjM0q$UGHA.5248@.TK2MSFTNGP10.phx.gbl...
> Hi
> I have an SP with a few params and I wish to use one of the params in the
> WHERE clause, to conditionaly set a WHERE statement, for example:
> CREATE PROC sp_Test
> @.ProductCode VARCHAR(5)
> @.ProcessMonth INT = NULL,
> @.ProcessYear INT = NULL
> AS
> SELECT Table.ID
> FROM Table
> WHERE
> Table.PMonth = @.ProcessMonth
> AND Table.PYear = @.ProcessYear
> AND
> IF @.ProductCode = 'ALL' THEN
> BEGIN
> Table.ProductCode = ('A','B','C' etc...all codes, need this
to
> be dynamic)
> END
> ELSE
> BEGIN
> Table.ProductCode = @.ProductCode
> END
> Hope this makes sense, I also don't know how to make the 'ALL' return all
> records?
> Kind Regards
> RickyP
>

Monday, March 19, 2012

Conditional update


Hello all, my update statement works as expected, but lacks some conditional logic. How can I change the statement to not decrement qtyonhand if the quantity is 0? Additionally, I would need to return to the calling application something that would allow me to populate a label with a message to the user.. How can that be accomplished?

Here is my sproc:
CREATE PROCEDURE [webuser].[cssp_removeItem]

@.lblID int

AS

Update cstb_inventory
set qtyonhand = qtyonhand -1
where Id = @.lblID
GO

Here is my app code:

Try

Dim cmdAs SqlCommand = cn.CreateCommand

cmd =New SqlCommand("cssp_removeItem", cn)

cmd.CommandType = CommandType.StoredProcedure

With cmd

cmd.Parameters.Add("@.lblId", SqlDbType.Int).Value = lblId.Text

EndWith

IfNot cn.State = ConnectionState.OpenThen

cn.Open()

EndIf

cmd.ExecuteNonQuery()

Catch exAs Exception

Response.Write(ex.ToString)

Finally

IfNot cn.State = ConnectionState.ClosedThen

cn.Close()

cn =Nothing

EndIf


(1) Get the quantity into a variable and check if its > 0, only then update.

(2) You can use an OUTPUT parameter to return values back to the application. To retrieve the value returned through an OUTPUT parameter add the parameter to the collection and set its direction to OUTPUT. Check the second part ofthis articlefor some code.

CREATE PROCEDURE [webuser].[cssp_removeItem] (
@.lblID int
,@.result int OUTPUT )
AS

BEGIN
SET NOCOUNT ON

DECLARE @.qty int

SET @.result = 0

SELECT
@.qty = qtyonhand
FROM
cstb_inventory
WHERE
Id = @.lblID

IF @.qty > 0
BEGIN

UPDATE
cstb_inventory
SET
qtyonhand = qtyonhand -1
WHERE
Id = @.lblID
SET @.result = @.@.ROWCOUNT

END


SET NOCOUNT OFF
END
GO

|||

Thanks! that helped out a lot.

|||CREATE PROCEDURE [webuser].[cssp_removeItem]

@.lblID int

AS

Update cstb_inventory
set qtyonhand = qtyonhand -1
where Id = @.lblIDAND qtyonhand>=1
GO

You can also use qtyonhand>0 if the field is an integer type.

|||

Thank you for responding. For those watching, this works.

CREATE PROCEDURE [webuser].[cssp_removeItem]

@.lblID int
, @.newvalue int OUTPUT
AS

Update cstb_inventory
set qtyonhand = qtyonhand -1
where Id = @.lblID
and qtyonhand > 0

SELECT @.newvalue =qtyonhand
FROM cstb_inventory
where Id = @.lblID
GO

And this:

Try

Dim cmdAs SqlCommand = cn.CreateCommand

cmd =New SqlCommand("cssp_removeItem", cn)

cmd.CommandType = CommandType.StoredProcedure

With cmd

cmd.Parameters.Add("@.lblId", SqlDbType.Int).Value = lblId.Text

cmd.Parameters.Add("@.newValue", SqlDbType.Int).Direction = ParameterDirection.Output

EndWith

IfNot cn.State = ConnectionState.OpenThen

cn.Open()

EndIf

cmd.ExecuteNonQuery()

lblMessage.Text = cmd.Parameters("@.newValue").Value.ToString()

If lblMessage.Text = 0Then

lblMessage2.Text ="There are no more parts at this location"

EndIf

Catch exAs Exception

Response.Write(ex.ToString)

Finally

IfNot cn.State = ConnectionState.ClosedThen

cn.Close()

cn =Nothing

EndIf

ProductGrid.DataBind()

EndTry

|||

Of course, if you had 1 before your call, you would still return the message that there are no more parts available, which I don't believe you want.

CREATE PROCEDURE [webuser].[cssp_removeItem]

@.lblID int
, @.newvalue int OUTPUT
AS

Update cstb_inventory
set qtyonhand = qtyonhand -1
where Id = @.lblID
and qtyonhand > 0

SELECT @.newvalue=@.@.Rowcount
GO

I think is what you want, not only does it save you the database query, but it will return 1 if there was a part available, or 0 if qtyonhand was already 0.

|||Way to go Motley! Your code is a better solution.

Conditional Sum Statement

Hey all,
Quick question, I have a field that I need to sum only when another
field is a certan value.
For example, a dataset with 5 fields {row_id, dealer_id, rep_id,
sales_code, sales_amt} and grouped by dealer_id then rep_id, I would
want to sum the sales_amt field when the first character of the
sales_code field is an 'X'. So for the set:
1, 1, 999, X100, $200.00
2, 1, 999, 200, $500.00
3, 1, 999, 898, $1000.00
4, 1, 555, X340, $2000.00
5, 1, 555, X444, $23.00
The resultant sums would be:
for dealer_id 1: 2223.00
for rep_id 999: 200.00
for rep_id 555: 2023.00
I am trying to do this in MRS as opposed to making it an additional
field in my querry.
Thanks!I think this is what you are asking...
And There is probably an easier way to do this but in the expression builder
IIF(SUBSTR(sales_code),1,1) = "x", Sum(sales_amt ),"")
Or something along those lines...
Hope that helps
Kerrie
Jimmy V wrote:
>Hey all,
>Quick question, I have a field that I need to sum only when another
>field is a certan value.
>For example, a dataset with 5 fields {row_id, dealer_id, rep_id,
>sales_code, sales_amt} and grouped by dealer_id then rep_id, I would
>want to sum the sales_amt field when the first character of the
>sales_code field is an 'X'. So for the set:
>1, 1, 999, X100, $200.00
>2, 1, 999, 200, $500.00
>3, 1, 999, 898, $1000.00
>4, 1, 555, X340, $2000.00
>5, 1, 555, X444, $23.00
>The resultant sums would be:
>for dealer_id 1: 2223.00
>for rep_id 999: 200.00
>for rep_id 555: 2023.00
>I am trying to do this in MRS as opposed to making it an additional
>field in my querry.
>Thanks!
--
Message posted via http://www.sqlmonster.com|||Kerrie,
I had to create a calculated field and summed it that way, i did use
your code snippit to generate my calculated field.
Thanks!!!|||Glad I could help, That is the best thing i have heard all day.
Thanks!
Jimmy V wrote:
>Kerrie,
>I had to create a calculated field and summed it that way, i did use
>your code snippit to generate my calculated field.
>Thanks!!!
--
Message posted via http://www.sqlmonster.com|||Hi Jimmy,
Easy way of doing is, if u want a sum by Sales order =x...., AND REP_ID
create a group with the sales order =x JUST "X" and u will get the value for
it
and then subtract this one with rest of value.
regards
JERROB
"Jimmy V" wrote:
> Hey all,
> Quick question, I have a field that I need to sum only when another
> field is a certan value.
> For example, a dataset with 5 fields {row_id, dealer_id, rep_id,
> sales_code, sales_amt} and grouped by dealer_id then rep_id, I would
> want to sum the sales_amt field when the first character of the
> sales_code field is an 'X'. So for the set:
> 1, 1, 999, X100, $200.00
> 2, 1, 999, 200, $500.00
> 3, 1, 999, 898, $1000.00
> 4, 1, 555, X340, $2000.00
> 5, 1, 555, X444, $23.00
> The resultant sums would be:
> for dealer_id 1: 2223.00
> for rep_id 999: 200.00
> for rep_id 555: 2023.00
> I am trying to do this in MRS as opposed to making it an additional
> field in my querry.
> Thanks!
>

Conditional statement with a cast from string to date

My source file is showing column 10 as string. My destination table is datetime. I am using the derived transformation with a conditional statement. How do I convert the value from string to date. Everywhere I try the (DT_DATE) I get an error.

[Column 10] == "01/01/0001" ? " 01/01/1801" : [Column 10] <= "12/31/1801" ? "12/31/1801" : [Column 10]

What's the error?|||

I modified it to the following but I get an error when I try to debug.

[Column 10] == "01/01/0001" ? (dt_date)" 01/01/1801" : [Column 10] <= "12/31/1801" ? (dt_date)"12/31/1801" : (dt_date)[Column 10]

Error message is:

...conversion between types dt_str and db_timestamp is not supported

|||What is the output column data type specified as in the derived column?|||Where do I check that? I only see the input defined in the derived column transformation which is dt_string 50. The column is defined as datetime in the table.|||http://ssistalk.blogspot.com/2007/01/derived-column.html

I would expect to see the data type of the derived column be DT_DBTIMESTAMP (or DT_DBDATE). The expression should be:

[column10] == "xxxxxx" ? "01/01/1801" : ......

Make sure "Derived Column" is set to "add as new column".|||I don't want to add it as a new column. I am using the conditional statement instead of the SQL case statement. I have dates from Oracle that are outside SQL's range that I need to convert.|||Right, but you can't replace the column because it's a DT_STR.... So if you want a date data type, you need to have a new column. This is the proper way to do it. Then in the data flow, you just ignore [column10] and use [DateColumn10], for instance.|||I tried that but now I get the same error for my new column10.|||

RMooreFL wrote:

I tried that but now I get the same error for my new column10.

Okay, I've posted a new example.

http://ssistalk.blogspot.com/2007/01/derived-column.html

Conditional Statement in a Group

Hi,
This probably has a simple answer.
This is what I am trying to do on a report , I am trying to get a count of a
condition where IsUnderInvestigation = "yes" where the report is grouped by
"TEAM"
Dataset:
ID Name Team IsUnderInvestigation
1 John X Yes
2 Michael Y No
3 Peter X Yes
Then the report is grouped by TEAM to produce and then a column of count of
if the field "IsUnderInvestigation" is yes, then it increments the counter
to produce teh following report.
Team How Many Investigations for Team
X 2
Y 0
So as you can see, I need to group the data by TEAM and then have a count of
how many people within each team are under investigation.
Does anyone know how to put this conditional count statement in a cell of
the report?
Thanks in advance for any help.
Kind Regards
WarrenTry this:
=Sum(iif(Fields!UnderInvestigation = "Yes", 1, 0))
-- Robert
This posting is provided "AS IS" with no warranties, and confers no rights.
"Warren Patterson" <des@.newsgroups.nospam> wrote in message
news:%23OKXMCeYFHA.4032@.tk2msftngp13.phx.gbl...
> Hi,
> This probably has a simple answer.
> This is what I am trying to do on a report , I am trying to get a count of
> a
> condition where IsUnderInvestigation = "yes" where the report is grouped
> by
> "TEAM"
> Dataset:
> ID Name Team IsUnderInvestigation
> 1 John X Yes
> 2 Michael Y No
> 3 Peter X Yes
> Then the report is grouped by TEAM to produce and then a column of count
> of
> if the field "IsUnderInvestigation" is yes, then it increments the counter
> to produce teh following report.
> Team How Many Investigations for Team
> X 2
> Y 0
>
> So as you can see, I need to group the data by TEAM and then have a count
> of
> how many people within each team are under investigation.
> Does anyone know how to put this conditional count statement in a cell of
> the report?
> Thanks in advance for any help.
> Kind Regards
> Warren
>
>
>
>
>|||Thank you thank you thank you thank you!
When I saw your solution, I thought....aish, I now look stoopid.
Kind Regards
Warren
"Robert Bruckner [MSFT]" <robruc@.online.microsoft.com> wrote in message
news:%23nK5qviYFHA.3184@.TK2MSFTNGP15.phx.gbl...
> Try this:
> =Sum(iif(Fields!UnderInvestigation = "Yes", 1, 0))
>
> -- Robert
> This posting is provided "AS IS" with no warranties, and confers no
rights.
>
> "Warren Patterson" <des@.newsgroups.nospam> wrote in message
> news:%23OKXMCeYFHA.4032@.tk2msftngp13.phx.gbl...
> > Hi,
> >
> > This probably has a simple answer.
> >
> > This is what I am trying to do on a report , I am trying to get a count
of
> > a
> > condition where IsUnderInvestigation = "yes" where the report is grouped
> > by
> > "TEAM"
> >
> > Dataset:
> > ID Name Team IsUnderInvestigation
> > 1 John X Yes
> > 2 Michael Y No
> > 3 Peter X Yes
> >
> > Then the report is grouped by TEAM to produce and then a column of count
> > of
> > if the field "IsUnderInvestigation" is yes, then it increments the
counter
> > to produce teh following report.
> >
> > Team How Many Investigations for Team
> > X 2
> > Y 0
> >
> >
> > So as you can see, I need to group the data by TEAM and then have a
count
> > of
> > how many people within each team are under investigation.
> >
> > Does anyone know how to put this conditional count statement in a cell
of
> > the report?
> >
> > Thanks in advance for any help.
> >
> > Kind Regards
> > Warren
> >
> >
> >
> >
> >
> >
> >
> >
> >
>

Conditional SQL Statements?

Hi There

I am writing a shopping cart page and I need some help in 'doing the math' for an SQL statement.

I have a main cart table that adds all the products.prices together from the 'price' field in the database to give the total amount payable.

SELECT SUM(TotPric) AS TheTotal FROM ( SELECT cart.cart_quantity * product_options.price AS TotPric FROM product_options INNER JOIN (products INNER JOIN (cart INNER JOIN main ON cart.main_id = main.main_id) ON products.product_id = main.product_id) ON product_options.product_options_id = main.product_options_id WHERE cart.session_id = "&cookiesesh&")AS TTT;"

I have however introduced a 'sale_price' that I would like the statement to select over the 'price' if the sale_price isn't 0.

Do I need to have another select statement in the mix to specifically select the sale_price if not zero, something like

SELECT SUM(TotPric) AS TheTotal FROM ( SELECT cart.cart_quantity * (SELECT product_options.price AS sp WHERE po.sale_price <> 0) AS TotPric FROM product_options INNER JOIN (products INNER JOIN (cart INNER JOIN main ON cart.main_id = main.main_id) ON products.product_id = main.product_id) ON product_options.product_options_id = main.product_options_id WHERE cart.session_id = "&cookiesesh&")AS TTT;"

I am a bit confused. Can you point me in the right direction, maybe a link to a tutorial or something.

I appreciate any help.

CheersRewritten for viewing

SELECT SUM(TotPric) AS TheTotal,
FROM (
SELECT (c.cart_quantity * po.price) AS TotPric
FROM product_options po
INNER JOIN main m ON po.product_options_id = m.product_options_id
INNER JOIN products p ON p.product_id = m.product_id
INNER JOIN cart c ON c.main_id=m.main_id
WHERE c.session_id = "&cookiesesh&"
) AS TTT"

Potential answer

SELECT SUM(TotPric) AS TheTotal,
FROM (
SELECT (c.cart_quantity * IF(po.sale_price>0,sale_price,price) AS TotPric
FROM product_options po
INNER JOIN main m ON po.product_options_id = m.product_options_id
INNER JOIN products p ON p.product_id = m.product_id
INNER JOIN cart c ON c.main_id=m.main_id
WHERE c.session_id = "&cookiesesh&"
) AS TTT"|||thanks aschk.|||Does it work? What DBMS are you using? Can you provide a sample table layout? Do you have some sample data for a test? If you could provide this information I'm sure I could give you a better answer.|||Hi Aschk

Its not working. Thanks for the effort though.

I am using MySQL.

Tables

tblCart
cart_id,session_id,main_id,cart_quantity,timestamp

tblProduct_Options
product_options_id, product_options_text,price,sale_price,stock

tblMain
main_id,product_id,product_options_id

tblProducts
product_id,product_name,description

(some fields removed for clarity)

I am basically trying to do is mutliply cart_quantity with the sale_price if the sale_price is not zero, if it is zero then multiply by the price.

I have included the sql_dump with all the data.

Thanks for your time and effort|||SELECT SUM(TotPric) as TheTotal
FROM (
SELECT (c.cart_quantity * IF(po.sale_price>0,sale_price,price)) AS TotPric
FROM product_options po
JOIN main m ON po.product_options_id = m.product_options_id
JOIN products p ON p.product_id = m.product_id
JOIN cart c ON c.main_id=m.main_id
WHERE c.session_id = '@.sessionid'
) ttt|||The original answer worked. Sorry aschk, I can't even copy and paste. time to hang up my coding hat and apply for that Burger King vacancy.

Thanks for your help and your time
:beer:
:)|||i was just looking through your table structure and had a question regarding a few columns you are using.

In your products table you are using a `text` column for your product name. I was wondering why? I suspect your names of products won't be larger than 255 variable characters so use a VARCHAR(255).

Also the same for your product_code and cart_finish columns in your cart and main tables. I can't see a reason why these need to be text columns either.

Maybe a rethink on those or explanation would be good ;) ?|||Thanks for pointing this out to me.

Definately a rethink.

I have recently moved from access to mysql and haven't really studied the benefits of choosing the right field type or best practises for mysql.

I am looking into it now.

Do you have any advice or know of any sites I can look at before I google it myself.

I am guessing that VARCHAR keeps the database size down & makes it quicker?|||In a word yes. I'm not 100% keyed up on the data types especially with regards to Text, however what I do is that it's a self altering column meaning that data could continually be placed in it and it could differ per row of the database. Unless you're dealing with text of an unknown size it's best to restrict fields to sensible values. e.g. usernames will probably be no longer than 30 characters and thus you column shouldn't need to be anything bigger than varchar(30).|||You know, using a subquery here is superfluous. This will return the same result with less obfuscation:
SELECT Sum((c.cart_quantity * IF(po.sale_price>0,sale_price,price)) AS TheTotal
FROM product_options po
JOIN main m ON po.product_options_id = m.product_options_id
JOIN products p ON p.product_id = m.product_id
JOIN cart c ON c.main_id=m.main_id
WHERE c.session_id = '@.sessionid'|||The IF thing is not SQL. A case expression has to be used:

SELECT SUM(c.cart_quantity * CASE po.sale_price > 0 THEN sale_price ELSE price END) AS theTotal
FROM ...|||The IF thing is not SQL.The poster does not indicate what platform he is using, but he did say that the code worked as written. You are correct that the statement is not in the correct syntax for MSSQL (or Oracle, I think), but it may execute for Access which is bastardized with VB.|||First of all: thanks Blindman and Stolze for the time you took in posting to this thread.

My Db is MySQL and I am using classic ASP to write the 'other bits'

I am a newb to this so I am a little lost when it comes to 'The IF thing is not SQL'

What I am trying to do is write fast, correct, standard code and I appreciate your input.

As Blindman pointed out the original query supplied by Aschk works fine, what I would like to know is: Are there performance gains to be made by losing the subquery, is it more 'standard and correct' to use, as Stolze said, the CASE expression instead.

I can see myself coming across this situation again and again and it would be good for me to get it right inthe future.

Thanks again for your input guys. enlightening and educating.

:)|||There are certainly no performance GAINS to be had by using unnecessary subqueries. If you are a consultant being paid to code by the line, then that method may work out well for you, but otherwise it just makes it more difficult to debug.|||The poster does not indicate what platform he is using, but he did say that the code worked as written. You are correct that the statement is not in the correct syntax for MSSQL (or Oracle, I think), but it may execute for Access which is bastardized with VB.

Here we discuss standardized SQL as defined in ISO/IEC 9075 (aka SQL:2003). That's why there is this sticky "Read This First" article: http://www.dbforums.com/announcement.php?f=11 So platform questions are usually irrelevant (except to state if a DBMS is conforming to SQL:2003 or not).

As for the question whether CASE expression or "the IF thing" is "more standard and correct", this is easy to answer: CASE expressions are defined in the SQL standard; so it is conforming to use that. "The IF thing" is not standard SQL and only a product-specific extension. If you want to write mostly portable SQL code (very hard btw), you shouldn't use it.|||Heh, if you're being paid line by line then space your work out, don't write subqueries ;)