Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Thursday, March 29, 2012

Edit connection manager connection string at runtime with c#

This is the first time I have used SSIS, so please bear with the ignorance.

I have a super simple package that inserts x000's of rows into a temporary table. The data source is a file that the user will upload. I need to be able to tell the package what file to upload. I'm thinking the simplest thing would be to edit the connectionString property of the SourceConnectionFlatFile at runtime. Is this possible? What form should the file path be in (UNC, other)? And, are there any other considerations I should be aware of?

Thanks!

Package configurations were designed for just this purpose.

Ecommerce account is logged in for a long time on SQL Server

I'm monitoring our SQL Server over the weekend to see what is happening with the Ecomm login account that allows nurses to renew licenses online. Using the standard trace template which has 2 events, "Audit Login" and "Audit Logout", I find that the avera
ge over the weekend for anything over 10 minutes is 70 minutes!
SELECT AVG(Duration / 60000) AS AverageOfMinutesLoggedIn
FROM AllNightStandardProfileForEcomm
WHERE (Duration / 60000 > 10)
Scratching my head here. Does that mean that the webserver (ecomm account using java and MS JDBC driver) logs in and stays logged in until the nurse is done? Is this done at the start of a sesssion? Does this make sense? In ADO connections you login, do t
he dirty deed, and then log out. Over and over. I'm thinking that the web people wrote the code to login at session start and logout at session end. Is that correct? I'm thinking no.
It does take a while for a nurse to renew her license(s) because they have to put in all sorts of continuing education credits. One nurse took 265 minutes! And her session was logged in to the database the whole time.
Any ideas, insites?
John
************************************************** ********************
Sent via Fuzzy Software @. http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
jdnospam@.hevanet.com wrote:

> I'm monitoring our SQL Server over the weekend to see what is happening
> with the Ecomm login account that allows nurses to renew licenses online.
> Using the standard trace template which has 2 events, "Audit Login" and
>"Audit Logout", I find that the average over the weekend for anything over 10 minutes is 70 minutes!
> SELECT AVG(Duration / 60000) AS AverageOfMinutesLoggedIn
> FROM AllNightStandardProfileForEcomm
> WHERE (Duration / 60000 > 10)
> Scratching my head here. Does that mean that the webserver (ecomm account
>using java and MS JDBC driver) logs in and stays logged in until the nurse
>is done? Is this done at the start of a sesssion? Does this make sense? In
> ADO connections you login, do the dirty deed, and then log out. Over and
>over. I'm thinking that the web people wrote the code to login at session
>start and logout at session end. Is that correct? I'm thinking no.
> It does take a while for a nurse to renew her license(s) because they have
>to put in all sorts of continuing education credits. One nurse took 265 minutes!
> And her session was logged in to the database the whole time.
> Any ideas, insites?
Hi. If the JDBC client is middleware, it may be pooling connections, which is a good thing.
However, if it's a simple client, then it may keep a connection for as long as it needs,
and if it's really poorly designed, it may start a transaction to do what the nurse wants,
and then hold the connection open and do updates as the nurse does, locking data till (s)he
finishes... Maybe the application could get a connection at the start to verify the DBMS
is up, then close it and collect all the data while *not* connected to the DBMS. Then,
when it's ready to submit, re-open the connection and do the update is one quick move.
Joe Weinstein at BEA
> John
> ************************************************** ********************
> Sent via Fuzzy Software @. http://www.fuzzysoftware.com/
> Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
|||jdnospam@.hevanet.com wrote:

> I'm monitoring our SQL Server over the weekend to see what is happening
> with the Ecomm login account that allows nurses to renew licenses online.
> Using the standard trace template which has 2 events, "Audit Login" and
>"Audit Logout", I find that the average over the weekend for anything over 10 minutes is 70 minutes!
> SELECT AVG(Duration / 60000) AS AverageOfMinutesLoggedIn
> FROM AllNightStandardProfileForEcomm
> WHERE (Duration / 60000 > 10)
> Scratching my head here. Does that mean that the webserver (ecomm account
>using java and MS JDBC driver) logs in and stays logged in until the nurse
>is done? Is this done at the start of a sesssion? Does this make sense? In
> ADO connections you login, do the dirty deed, and then log out. Over and
>over. I'm thinking that the web people wrote the code to login at session
>start and logout at session end. Is that correct? I'm thinking no.
> It does take a while for a nurse to renew her license(s) because they have
>to put in all sorts of continuing education credits. One nurse took 265 minutes!
> And her session was logged in to the database the whole time.
> Any ideas, insites?
Hi. If the JDBC client is middleware, it may be pooling connections, which is a good thing.
However, if it's a simple client, then it may keep a connection for as long as it needs,
and if it's really poorly designed, it may start a transaction to do what the nurse wants,
and then hold the connection open and do updates as the nurse does, locking data till (s)he
finishes... Maybe the application could get a connection at the start to verify the DBMS
is up, then close it and collect all the data while *not* connected to the DBMS. Then,
when it's ready to submit, re-open the connection and do the update is one quick move.
Joe Weinstein at BEA
> John
> ************************************************** ********************
> Sent via Fuzzy Software @. http://www.fuzzysoftware.com/
> Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
|||Very good observation. I think the operative words here are:
"collect all the data while *not* connected to the DBMS".
I shudder mentioning "connection pooling" to them. NO MORE FANCY STUFF!!!
Get in, get the money, get out.
Anything else you want to comment on I would be all ears. I know they are holding everything in sessions variables, but I'm thinking they should put it all in a de-normalized holding table. Once the payment goes through, then Bang! the database gets up da
ted and we have an extra place to look to troubleshoot. Anything in a session dies when the session dies.
One other question, is the session starting when they open the browser or when they successfully login with their ID/whatever. Off topic but hey.
Cheers,
John Davis
OSBN
************************************************** ********************
Sent via Fuzzy Software @. http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
|||jdnospam@.hevanet.com wrote:

> Very good observation. I think the operative words here are:
> "collect all the data while *not* connected to the DBMS".
> I shudder mentioning "connection pooling" to them. NO MORE FANCY STUFF!!!
> Get in, get the money, get out.
Good luck.

> Anything else you want to comment on I would be all ears. I know they
>are holding everything in sessions variables, but I'm thinking they
>should put it all in a de-normalized holding table. Once the payment
> goes through, then Bang! the database gets up dated and we have an
>extra place to look to troubleshoot. Anything in a session dies when the session dies.
> One other question, is the session starting when they open the browser or
> when they successfully login with their ID/whatever. Off topic but hey.
> Cheers,
> John Davis
> OSBN
> ************************************************** ********************
> Sent via Fuzzy Software @. http://www.fuzzysoftware.com/
> Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...

Monday, March 26, 2012

easy parameter Q

I think this is probably easy but haven't found the setting yet and am
running out of time.
My report has a column I want to use as a parameter(parameter query). The
value of the field repeats several times and I want to limit the drop down
list to the first occurance of each value.
Hope this is an easy one.Have you tried select Distinct(column) ?
"HollyylloH" wrote:
> I think this is probably easy but haven't found the setting yet and am
> running out of time.
> My report has a column I want to use as a parameter(parameter query). The
> value of the field repeats several times and I want to limit the drop down
> list to the first occurance of each value.
> Hope this is an easy one.|||Darwin,
Thanks for your reply. I am using report parameters and am not sure how to
use a distinct() within the confines of the the parameter options. If you can
help I would much appriciate it.
I don't want to affect the report query but rather the parameter drop-down
menu options.
"darwin" wrote:
> Have you tried select Distinct(column) ?
> "HollyylloH" wrote:
> > I think this is probably easy but haven't found the setting yet and am
> > running out of time.
> >
> > My report has a column I want to use as a parameter(parameter query). The
> > value of the field repeats several times and I want to limit the drop down
> > list to the first occurance of each value.
> >
> > Hope this is an easy one.|||create a new dataset to use to populate the parameter. You can create
multiple datasets to populate your parameters.
then change your parameter properties to use the new data set. select the
parameter you want to change, then click the From Query radio button, select
the new dataset name under dataset, select the Value Field value and the
label field. This is generally an Id and description.
hope that helps.. there should be something thats helps in the help files
"HollyylloH" wrote:
> Darwin,
> Thanks for your reply. I am using report parameters and am not sure how to
> use a distinct() within the confines of the the parameter options. If you can
> help I would much appriciate it.
> I don't want to affect the report query but rather the parameter drop-down
> menu options.
> "darwin" wrote:
> > Have you tried select Distinct(column) ?
> >
> > "HollyylloH" wrote:
> >
> > > I think this is probably easy but haven't found the setting yet and am
> > > running out of time.
> > >
> > > My report has a column I want to use as a parameter(parameter query). The
> > > value of the field repeats several times and I want to limit the drop down
> > > list to the first occurance of each value.
> > >
> > > Hope this is an easy one.|||Thanks a million! That did it for me!
"darwin" wrote:
> create a new dataset to use to populate the parameter. You can create
> multiple datasets to populate your parameters.
> then change your parameter properties to use the new data set. select the
> parameter you want to change, then click the From Query radio button, select
> the new dataset name under dataset, select the Value Field value and the
> label field. This is generally an Id and description.
> hope that helps.. there should be something thats helps in the help files
>
> "HollyylloH" wrote:
> > Darwin,
> >
> > Thanks for your reply. I am using report parameters and am not sure how to
> > use a distinct() within the confines of the the parameter options. If you can
> > help I would much appriciate it.
> >
> > I don't want to affect the report query but rather the parameter drop-down
> > menu options.
> >
> > "darwin" wrote:
> >
> > > Have you tried select Distinct(column) ?
> > >
> > > "HollyylloH" wrote:
> > >
> > > > I think this is probably easy but haven't found the setting yet and am
> > > > running out of time.
> > > >
> > > > My report has a column I want to use as a parameter(parameter query). The
> > > > value of the field repeats several times and I want to limit the drop down
> > > > list to the first occurance of each value.
> > > >
> > > > Hope this is an easy one.

Thursday, March 22, 2012

Easy Date Problem

I am somewhat new to SQL and was trying to subtract 11 days from today
but I want it to go to 00:00:00 rather than 11 days whatever time it is
I run it.
Example: It is 8:39 AM right now and when I run
where completiondate BETWEEN getdate()-11 and getdate()-5
I want the result to be xx/xx/xx 00:00:00 rather than xx/xx/xx 8:39.
Thanks!
BVDECLARE @.dt SMALLDATETIME
SET @.dt = DATEDIFF(DAY,0,GETDATE())
SELECT @.dt
SELECT ...
WHERE CompletionDate >= (@.dt - 11)
AND CompletionDate < (@.dt - 5)
(Do not use between here, unless CompletionDate *only* stores the date with
time always set to midnight, and if you want to include rows from 5 days ago
in the result.)
<brentkelli@.gmail.com> wrote in message
news:1130420498.749859.291940@.g49g2000cwa.googlegroups.com...
>I am somewhat new to SQL and was trying to subtract 11 days from today
> but I want it to go to 00:00:00 rather than 11 days whatever time it is
> I run it.
> Example: It is 8:39 AM right now and when I run
> where completiondate BETWEEN getdate()-11 and getdate()-5
> I want the result to be xx/xx/xx 00:00:00 rather than xx/xx/xx 8:39.
> Thanks!
> BV
>|||How is about?
SELECT <columns> FROM Table WHERE completiondate
>=CAST(FLOOR(CAST(DATEADD(day,-11,GETDATE())AS FLOAT))AS DATETIME)AND
<=CAST(FLOOR(CAST(DATEADD(day,-11,GETDATE())AS FLOAT))AS DATETIME)
<brentkelli@.gmail.com> wrote in message
news:1130420498.749859.291940@.g49g2000cwa.googlegroups.com...
>I am somewhat new to SQL and was trying to subtract 11 days from today
> but I want it to go to 00:00:00 rather than 11 days whatever time it is
> I run it.
> Example: It is 8:39 AM right now and when I run
> where completiondate BETWEEN getdate()-11 and getdate()-5
> I want the result to be xx/xx/xx 00:00:00 rather than xx/xx/xx 8:39.
> Thanks!
> BV
>

easier email alerts from sql 7/2000?

hi,

i get just as frustrated each time i try to configure email alerts on failed jobs on ms sql, it is beyond me why microsoft couldn't just let you point out an SMTP server to send through and be done with it.

is there a way to avoid having to setup an email client on our sql 7 and 2000 servers through some 3rd party app or other simple solution?

thanks in advance,
danielhi,

is there a way to avoid having to setup an email client on our sql 7 and 2000 servers through some 3rd party app or other simple solution?

thanks in advance,
daniel

Amen, brother!

You do have some options:

1. There are some 3rd party tools to (sort of) accomplish what you are trying to do. They are not supported, however. Look at www.sqldev.net.

2. You can add additional steps to the jobs you wish to monitor (and set the task order to on failure).

3. You can upgrade to SQL 2005. This is not quite as awful as it sounds and getting to Database Mail (which is SMTP) is a major benefit!

Regards,

hmscott|||Amen, brother!

You do have some options:

1. There are some 3rd party tools to (sort of) accomplish what you are trying to do. They are not supported, however. Look at www.sqldev.net.

2. You can add additional steps to the jobs you wish to monitor (and set the task order to on failure).

3. You can upgrade to SQL 2005. This is not quite as awful as it sounds and getting to Database Mail (which is SMTP) is a major benefit!

Regards,

hmscott
1. thanks, i'll check them out. but maybe it's just easier to parse the errorlogs of both servers for failed backups from some php script.

2. do you mean add a step with the "operating system command" type and execute some external program to send alerts?

3. the sql7 server hosts 67 databases, the sql2000 server hosts 38, most of them production databases so it's still a scary thought time-wise :)

Wednesday, March 21, 2012

each time I build program, data is lost

I am using visual basic 2008

I am making a program, I used sql server compact edition (sdf) (i think it is no more only for mobile device, I am working for desktop application)which i created with the same visual basic. i update data by using table adapters,

when I close the program and build again, the data previosly updated are deleted, and I get empty database? why is that. do i need to set some copy to.........properties. i have used copy if new.

I want to add something to it, that when I manually entered data, they are not gone. But when I entered from form, next time the data lost.|||

See this: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2115234&SiteID=1

Dynamicaly add charts to report

I need display some processes (lines in a chart) in the report. One process
per chart. The number of processes is not known at the design time and is
defined by the result of the underlying report query, so I do not know how
many chart objects to place on the report at design time. Is it possible to
add charts dynamically to the report during the run time?
Any hint would be greatly appreciated.
Thanks.Maybe this will help!
I create a group (detail) line and I add a chart to this group by defining a
chart in one of the text boxes...
hen do the normal things with a chart - but the chart is automatically
GROUPED for you based upon the results of your query (in line or T-SQL)
"Simon Gold" wrote:
> I need display some processes (lines in a chart) in the report. One process
> per chart. The number of processes is not known at the design time and is
> defined by the result of the underlying report query, so I do not know how
> many chart objects to place on the report at design time. Is it possible to
> add charts dynamically to the report during the run time?
> Any hint would be greatly appreciated.
> Thanks.
>

Dynamically switching report data connection at run time

We have been presented with the problem of using Reporting Services to run
the same report against one of two databases.
We are currently using SQL Server 2000, and while 2005 has support for
dynamically building connection strings with parameters, 2000 apparently does
not.
Thus far, we have found the following solutions:
- A custom data processing extension, which wraps up a SqlConnection, and
switches database context at run-time based on an expected query parameter
- Reporting against a front-end query on the database, which in turn calls
the query from the desired database
- Installing two versions of the same report on the report server, and
having the application choose which to execute at run-time.
Each of these options has various drawbacks, the first brings with it a mess
of support and deployment issues, the second leans on the database harder
than it needs to, and the third is basically redundant.
Although the solution we need now is to switch between one of two databases,
the ideal solution would be able to manage 1-n databases.
We would appreciate your input as to which solution is the best, or if there
is functionality which would better suit our needs that we havenâ't discovered
yet.On Nov 16, 4:07 pm, breedReed <br...@.community.nospam> wrote:
> We have been presented with the problem of using Reporting Services to run
> the same report against one of two databases.
> We are currently using SQL Server 2000, and while 2005 has support for
> dynamically building connection strings with parameters, 2000 apparently does
> not.
> Thus far, we have found the following solutions:
> - A custom data processing extension, which wraps up a SqlConnection, and
> switches database context at run-time based on an expected query parameter
> - Reporting against a front-end query on the database, which in turn calls
> the query from the desired database
> - Installing two versions of the same report on the report server, and
> having the application choose which to execute at run-time.
> Each of these options has various drawbacks, the first brings with it a mess
> of support and deployment issues, the second leans on the database harder
> than it needs to, and the third is basically redundant.
> Although the solution we need now is to switch between one of two databases,
> the ideal solution would be able to manage 1-n databases.
> We would appreciate your input as to which solution is the best, or if there
> is functionality which would better suit our needs that we haven't discovered
> yet.
I would personally create a SQL Server instance that has Linked
Servers to your two other databases, then in reporting services pass
the SELECT * FROM OPENQUERY( @.ServerName, 'SELECT real SQL here' )
-- Scott

Sunday, March 11, 2012

Dynamically Create Connection Managers @ Run time

Is there a way to dynamically create a connection manager @. run time? I would like to do this from a data set of connection strings so I can link them into a union all component.

No. You cannot change package structure at run-time. You can dynamically read information in at run-time, so you can change your connection string for example. The best method is the build in Configuration support. You can also drive most properties through Expressions and supply a variable to set the property. Variables can be set in several ways, including other expressions and script tasks.

To load data from multiple sources, try using the For Each Loop, and drive this off your list of "connections". This can contain a data flow task, the connection of which can be updated on each loop iteration.

Try this article to give you an idea of looping with recordsets.

Shredding a Recordset
(http://www.sqlis.com/default.aspx?59)

Friday, March 9, 2012

Dynamically collapsing textboxes (and adjusting layout)

Just curious if there's a way I can remove a field from my report at run time and shift all the fields underneath it up.

I basically want to end up with the following:

Design time=============================Field 1: Fields!Field1.ValueField 2: Fields!Field2.Value// This one will be blankField 3: Fields!Field3.ValueField 4: Fields!Field4.ValueRun Time - eliminate any blank fields=============================Field 1:"Data 1"Field 3:"Data 3"Field 4:"Data 4"
 
Problem is, if I set the visibility of the field to false, it still takes up space on the form (as it should). Any suggestions as to how to shift all the fields up without using a table?
 
 
Thanks!

I guess I should clairify a bit

This is what is happening now:

Run Time - eliminate any blank fields=============================Field 1:"Data 1"Field 3:"Data 3"Field 4:"Data 4"I want to collapse Field 2 up so that thereis no whitespace between 1 and 3
 
 
Not sure if this is even possible...

Dynamically changing reports at runtime

Hi - I'm trying to decide among reporting options without spending too much
time going down the wrong path, so I hope someone can answer my questions
about Reporting Services capabilities...
With Reporting Services, can I dynamically (at runtime via code):
1) add or remove subreports from a report?
2) make a subreport visible or hidden?
3) add or delete columns?
4) make columns visible or hidden?
5) add or delete tables?
6) make a table visible or hidden?
Is doing any of these things fairly straightforward?
Thanks so much in advance,
SherylYes, you can use an expression for the Hidden property of respective report
elements to dynamically show/hide them at runtime.
--
Ravi Mumulla (Microsoft)
SQL Server Reporting Services
This posting is provided "AS IS" with no warranties, and confers no rights.
"Sheryl Landon" <shland@.comcast.net> wrote in message
news:OoDKy5$pEHA.3244@.tk2msftngp13.phx.gbl...
> Hi - I'm trying to decide among reporting options without spending too
much
> time going down the wrong path, so I hope someone can answer my questions
> about Reporting Services capabilities...
> With Reporting Services, can I dynamically (at runtime via code):
> 1) add or remove subreports from a report?
> 2) make a subreport visible or hidden?
> 3) add or delete columns?
> 4) make columns visible or hidden?
> 5) add or delete tables?
> 6) make a table visible or hidden?
> Is doing any of these things fairly straightforward?
> Thanks so much in advance,
> Sheryl
>

Dynamically CHange Table Name

Hi All...
How to dynamically change the Table name which i have use at design time. if old and new table contains same fields but changing only table name.(Old- at Design Time
New - At Run TIme)

I would prefer not to have to go through the hassle of manually opening up my Crystal Report documents in Visual Studio and setting their new table name each and every time I want to make a change to the table name dynamically.

Hope So....
Thanks in Advance.

Regards
Henry Jones.I think this is difficult to do this
See if you find solution here
http://support.businessobjects.com/

Wednesday, March 7, 2012

Dynamically Add Data to Crystal Report from Different Tables

Hi All
I am sending query to the Crystal report which i have designed.
but at design time i am using table1.
At run time i am sending query which contains table2 .
Table1 and Table2 are same it differs only in data, all fields are same.
Can i send the query to crystal report at run time if my crystal report(at design time) is using group by field at design time.
It's giving error of HResult exception.
Can we provide Multiple Tables Data at dynamically???
I am using crystal report 8.5 n SQL Server 2000

Plz Help me if anybody knows abt it.

Thanks in Advance

Regards
Henry JonesHi,

Yes u can, tell me whats u r Client Application is made of
Claasic VB, VS 2003/2005 Languages ???

Favaz|||See if you find code samples here
http://support.businessobjects.com/

Dynamic YTD based on user selection on Month

I have a user how wants to be able to see the YTD numbers based on the month they select in an attribute hierarchy with in the Time Dimension.

I would like to create a calculated member called YTD that they can use to get this information based on the Month they select in the Month attribute

The Time Dimensions are as follows: Fiscal time(Year, Qtr, Month) Month(Month)

Measure = Net Sales

View Format should be

Years

2000 2001 2002 2003 2004 2005

Customer $ $ $ $ $ $

YTD should work if the user drills down to Qtr or Month, if they selected a member in the Month attribute or not.

The Time dimension is only loaded with the years that are in the cube so if the user selects Dec but no data is in the cube for Dec 2005. 2005 should still show up on the report.

One of the issues I have run into is determining if the user is looking(selected) something from the Fiscal Hierarchy of from the Month Attirbute. If I use [Time].[Month].currentmember.name I get the name of the month the user selected in Month Attribute but if the user selects "All" months in the Month attribute but selects the Months from the Fiscal hierarchy I still get the month name and not the value "All".

Please Help.

Here is an example of a calculated member that I added to the "AdventureWorks" cube that will return the "Calendar" YTD internet sales amount based on what has been selected as the current member of the Date.Calendar hierarchy. The MDX will also work in AS2K.

Create Member CurrentCube.[Measures].[CYTD Internet Sales Amount]

AS

Aggregate(

PeriodsToDate(

[Date].[Calendar].[Calendar Year],

[Date].[Calendar].CurrentMember),

Measures.[Internet Sales Amount]),

Format_String = "Currency",

Non_Empty_Behavior = { Measures.[Internet Sales Amount] };

HTH,

- Steve

Dynamic WHERE Clause to Stored Procedure

Hi all!
I need to create a stored procedure with a parameter and then send a WHERE clause to that parameter (fields in the clause may vary from time to time thats why I want to make it as dynamic as possible) and use it in the query like (or something like) this:

----------------
@.crit varchar(100)

SELECT fldID, fldName FROM tblUsers
WHERE @.crit
----------------

Of course this does not work, but I don't know how it should be done, could someone please point me in the right direction on how to do this kind of queries.

cheers!
pelleU just pass a parameter @.crit into ur stored procedure and do the following with it inside:

EXEC('SELECT fldID, fldName FROM tblUsers WHERE' + @.crit );

This should help u... I hope.
Alex.|||Another example:


CREATE PROCEDURE [dbo].[Alter_Email_Users_Table]
(@.Column as nvarchar(50),
@.FieldType as nvarchar(50),
@.TableName as nvarchar(50),
@.Null as nvarchar(20),
@.Default as nvarchar(4000)
)
AS
Declare @.SQL nVarchar(4000)
Select @.SQL = 'ALTER TABLE ' + @.TableName + ' ADD ' + @.Column + ' ' + @.FieldType + ' ' + @.NULL + ' '
IF @.Default IS NOT NULL
SET @.SQL = @.SQL + ' Default ' + "'" + @.Default + "'"
exec (@.SQL)
GO

exec is the key part in both examples.

Dynamic WHERE Clause

Hi
I have a query which has a few different Time Period columns:
Half_Year (H1,H2)
Quarters (Q1,Q2,Q3,Q4)
Months (M1,M2,M3,... M12)
These periods are held in three difference columns.
I need to run this query with 2 params. One will be the year and other will
be one of the above three:
i.e
sp_Rating 2005, 'H1'
This is all transactions in months 1=6 for the year 2005.
or sp_Rating 2005, 'Q3' or sp_Rating 2005, 'M7'
How can I dynamically interrogate the correct column, based on the param
supplied (H, Q, M) ?
Kind Regards
Ricky
(WIN2K,SQL2K-SP4)Ricky (ricky@.msn.com) writes:
> I have a query which has a few different Time Period columns:
> Half_Year (H1,H2)
> Quarters (Q1,Q2,Q3,Q4)
> Months (M1,M2,M3,... M12)
> These periods are held in three difference columns.
> I need to run this query with 2 params. One will be the year and other
> will be one of the above three:
> i.e
> sp_Rating 2005, 'H1'
> This is all transactions in months 1=6 for the year 2005.
> or sp_Rating 2005, 'Q3' or sp_Rating 2005, 'M7'
> How can I dynamically interrogate the correct column, based on the param
> supplied (H, Q, M) ?
First of all, don't call your procedures sp_something. That prefix is
reserved for system procedures, and SQL Server first looks for a
procedure with such a name in the master database.
As for the question, I'm afraid that I dno't really understand. Does
this table has three columns? May then I ask the stupid question if
H1 can appear together with M7 to M12? I realise that if periodisation
takes place, this can happen. Then again, could a row really have
H1, Q3 and M10?
If you need all three columns try this:
SELECT ...
FROM tbl
WHERE (Halt_year = @.period AND @.period LIKE 'H%')
OR (Quarter = @.period AND @.period LIKE 'Q%')
OR (Months = @.period AND @.period LIKE 'M%')
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|||>> I have a query which has a few different Time Period columns: <<
Really? Mind showing us? Please post DDL, so that people do not have
to guess what the keys, constraints, Declarative Referential Integrity,
data types, etc. in your schema are. Sample data is also a good idea,
along with clear specifications. It is very hard to debug code when
you do not let us see it.
Why? Are they LOGICALLY DIFFERENT? There is usually only one kind of
time in the universe. Try a proper design:
CREATE TABLE PeriodCalendar
(period_name CHAR(15) NOT NULL PRIMARY KEY
start_date DATETIME NOT NULL,
end_date DATETIME NOT NULL);
INSERT INTO PeriodCalendar ('Q1-2006', '2006-01-01', '2006-03-341');
etc. for all the possible fiscal, marketing and calendaral periods you
use.
Again, not a good design; you seem to think that a year should be an
integer, while the ANSI standard say it is a CHAR(4); get a copy of the
8601 standards, too. Now life a JOIN and a BETWEEN predicate.
And you have already been told about not using "sp_" prefixes because
they refer to where something is phycially located as well as having a
special meaning in SQL Server.|||Thanks guys for the reply, I'm ashamed to say that I have been using the
'sp_' prefix, I did no know that this was the case, I shall rename mine to
something else today/tomorrow.
Kind Regards
Ricky
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1149463964.082284.170110@.i39g2000cwa.googlegroups.com...
> Really? Mind showing us? Please post DDL, so that people do not have
> to guess what the keys, constraints, Declarative Referential Integrity,
> data types, etc. in your schema are. Sample data is also a good idea,
> along with clear specifications. It is very hard to debug code when
> you do not let us see it.
>
> Why? Are they LOGICALLY DIFFERENT? There is usually only one kind of
> time in the universe. Try a proper design:
> CREATE TABLE PeriodCalendar
> (period_name CHAR(15) NOT NULL PRIMARY KEY
> start_date DATETIME NOT NULL,
> end_date DATETIME NOT NULL);
> INSERT INTO PeriodCalendar ('Q1-2006', '2006-01-01', '2006-03-341');
> etc. for all the possible fiscal, marketing and calendaral periods you
> use.
>
other will be one of the above three: sp_Rating 2005, 'H1' <<
> Again, not a good design; you seem to think that a year should be an
> integer, while the ANSI standard say it is a CHAR(4); get a copy of the
> 8601 standards, too. Now life a JOIN and a BETWEEN predicate.
> And you have already been told about not using "sp_" prefixes because
> they refer to where something is phycially located as well as having a
> special meaning in SQL Server.
>|||That's a mistake that we all make, until someone points out to us the
dangers.
In addition to what --CELKO-- posted, check out this article on calendar
tables, which goes into much more detail.
http://www.aspfaq.com/show.asp?id=2519
"ricky" <ricky@.ricky.com> wrote in message
news:O5wFxWHiGHA.4044@.TK2MSFTNGP03.phx.gbl...
> Thanks guys for the reply, I'm ashamed to say that I have been using the
> 'sp_' prefix, I did no know that this was the case, I shall rename mine to
> something else today/tomorrow.
> Kind Regards
> Ricky
>
> "--CELKO--" <jcelko212@.earthlink.net> wrote in message
> news:1149463964.082284.170110@.i39g2000cwa.googlegroups.com...
> other will be one of the above three: sp_Rating 2005, 'H1' <<
>|||Joe,
Just curious, what is the reason for making year a varchar instead of an
integer (in the standard)?
I have always thought of it as an integer that one might add and subtract
from for various date functions (of course leap year can complicate it).
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1149463964.082284.170110@.i39g2000cwa.googlegroups.com...
> Again, not a good design; you seem to think that a year should be an
> integer, while the ANSI standard say it is a CHAR(4); get a copy of the
> 8601 standards, too. Now life a JOIN and a BETWEEN predicate.|||
--CELKO-- wrote:

>Again, not a good design; you seem to think that a year should be an
>integer, while the ANSI standard say it is a CHAR(4); get a copy of the
>8601 standards, too. Now life a JOIN and a BETWEEN predicate.
>
ANSI 8601 is a standard for the "representation" of dates and times.
It's not a standard for how to store them. If you think the ANSI standard
says that a year *is* a char(4), please quote the relevant section of the
standard.
My copy of the standard says only that "In *expressions* of calendar
dates, year is generally *represented* by four digits..." [emphasis mine]
Steve Kass
Drew University
http://www.stevekass.com|||>> Just curious, what is the reason for making year a varchar instead of an
integer (in the standard)? <<
Mostly history. We based the SQL Standard on the pre-existing the
ISO-8601 Standards which is for display; it says nothing about internal
storage. We wanted to avoid anything to do with internal storage, like
specifying the use of numbers for dates.
You can see this with the specs for "EXTRACT(<temporal unit> FROM
<temporal exp)>" and the fact you have to use strings with "INTERVAL
<exp> <temporal unit>"; that is "INTERVAL '12' YEAR" works and
"INTERVAL 12 YEAR" is an error. What newbies will do is use integers
and force a casting in certain places.
Of course, by the time we got something into SQL, each vendor had a
proprietary library and storage method which was exposed to the users.
Rats!!|||
--CELKO-- wrote:

>Mostly history. We based the SQL Standard on the pre-existing the
>ISO-8601 Standards which is for display; it says nothing about internal
>storage. We wanted to avoid anything to do with internal storage, like
>specifying the use of numbers for dates.
>You can see this with the specs for "EXTRACT(<temporal unit> FROM
><temporal exp)>" and the fact you have to use strings with "INTERVAL
><exp> <temporal unit>"; that is "INTERVAL '12' YEAR" works and
>"INTERVAL 12 YEAR" is an error. What newbies will do is use integers
>and force a casting in certain places.
>
The reason the <interval string> is a string is that its domain is not
<integer>. The domain includes '1-4', for example.
This has nothing whatsoever to do with the issue of whether ANSI 8601
says that
a "year is a char(4)" (it does not).
SK

>Of course, by the time we got something into SQL, each vendor had a
>proprietary library and storage method which was exposed to the users.
> Rats!!
>
>|||I apologise if I have caused a disagreement, but is there an issue, if I do
format YEAR as an INT?
"Steve Kass" <skass@.drew.edu> wrote in message
news:uZknxeMiGHA.4080@.TK2MSFTNGP03.phx.gbl...
>
> --CELKO-- wrote:
>
an integer (in the standard)? <<
> The reason the <interval string> is a string is that its domain is not
> <integer>. The domain includes '1-4', for example.
> This has nothing whatsoever to do with the issue of whether ANSI 8601
> says that
> a "year is a char(4)" (it does not).
> SK
>

Sunday, February 19, 2012

Dynamic SQL with output values

Hi:
How can I in SQL Server 2000 (using Transact SQL) execute a dynamic sql string and at the same time retrieve output params ?
ThanksPlease give a specific example. What are the output parameters ? Are they based on the dynamic sql ? Where are you retrieving the output parameters from ?|||Originally posted by rnealejr
Please give a specific example. What are the output parameters ? Are they based on the dynamic sql ? Where are you retrieving the output parameters from ?

Here's an simple example:

SELECT @.num_records = COUNT(*)
FROM @.TableName

Friday, February 17, 2012

Dynamic SQL is faster.

Hi I have a stored proc -
takes a long time to execute so re-compilation isn't an issue.
I pass a comma separated varchar param to the stored procedure.
exec sp_somename @.CSV = '1,2,3'
If I build the SQL statement in the SP and then execute the statement
dynamically:
EXEC ('SELECT * FROM table1, ... other tables WHERE ID IN (1,2,3,4) ...rest
of sql'
as opposed to this,
having populated a temp table #t with @.CSV values.
SELECT * FROM
table1, #t, ... other tables
WHERE
table1.ID = #t.ID
...rest of sql
I used a function and SP to populate the #t; all took negliable speed.
The dynamic SQL performs twice as fast as the temp table/variable method.
Surprised I thought SELECT IN (.....) was converted into a join and would
be just as fast
Don't like Dynamic SQL if I can avoid it.Do you have any indexes on the temp table? if not, would one help on the
joined column?
David Gugick
Imceda Software
www.imceda.com
"Yitzak" <terryshamir@.bob.com> wrote in message
news:prG2e.903$VN1.310@.newsfe1-win.ntli.net...
> Hi I have a stored proc -
> takes a long time to execute so re-compilation isn't an issue.
> I pass a comma separated varchar param to the stored procedure.
> exec sp_somename @.CSV = '1,2,3'
>
> If I build the SQL statement in the SP and then execute the statement
> dynamically:
> EXEC ('SELECT * FROM table1, ... other tables WHERE ID IN (1,2,3,4)
> ...rest
> of sql'
> as opposed to this,
> having populated a temp table #t with @.CSV values.
> SELECT * FROM
> table1, #t, ... other tables
> WHERE
> table1.ID = #t.ID
> ...rest of sql
> I used a function and SP to populate the #t; all took negliable speed.
> The dynamic SQL performs twice as fast as the temp table/variable method.
> Surprised I thought SELECT IN (.....) was converted into a join and would
> be just as fast
> Don't like Dynamic SQL if I can avoid it.
>
>|||I thought because the table was so small at most having 10 rows - they would
be no benefit but I'll give it a go.
Thanks
"David Gugick" <davidg-nospam@.imceda.com> wrote in message
news:#DuCivYNFHA.3192@.TK2MSFTNGP10.phx.gbl...
> Do you have any indexes on the temp table? if not, would one help on the
> joined column?
> --
> David Gugick
> Imceda Software
> www.imceda.com
>
> "Yitzak" <terryshamir@.bob.com> wrote in message
> news:prG2e.903$VN1.310@.newsfe1-win.ntli.net...
method.
would
>|||Put some indexes on and did improve performance.
Changed some other stored procedures but still Dynamic SQL wins out. Thats
not to mention its clear advantage when you can easily optimise for no ids
e.g. @.param = '' by not including the IN statement in the SQL string
executed.
Just don't like Dynamic SQL - sp_depnds wont work. All the security issues.
but looks like I gotta use it.|||>> I pass a comma separated varchar param to the stored procedure. <<
Ever hear about First Normal Form (1NF)?
Pardon the fact that this "cut & paste" is in Standard SQL and not
dialect. Passing a list of parmeters to a stored procedure can be done
by putting them into a string with a separator. I like to use the
traditional comma. Let's assume that you have a whole table full of
such parameter lists:
CREATE TABLE InputStrings
(keycol CHAR(10) NOT NULL PRIMARY KEY,
input_string VARCHAR(255) NOT NULL);
INSERT INTO InputStrings VALUES ('first', '12,34,567,896');
INSERT INTO InputStrings VALUES ('second', '312,534,997,896');
..
This will be the table that gets the outputs, in the form of the
original key column and one parameter per row.
CREATE TABLE Parmlist
(keycol CHAR(10) NOT NULL PRIMARY KEY,
parm INTEGER NOT NULL);
It makes life easier if the lists in the input strings start and end
with a comma. You will need a table of sequential numbers -- a
standard SQL programming trick, Now, the real query, in SQL-92 syntax:
INSERT INTO ParmList (keycol, parm)
SELECT keycol,
CAST (SUBSTRING (I1.input_string
FROM S1.seq
FOR MIN(S2.seq) - S1.seq -1)
AS INTEGER)
FROM InputStrings AS I1, Sequence AS S1, Sequence AS S2
WHERE SUBSTRING ( ',' || I1.input_string || ',' FROM S1.seq FOR 1) =
','
AND SUBSTRING (',' || I1.input_string || ',' FROM S2.seq FOR 1) =
','
AND S1.seq < S2.seq
GROUP BY I1.keycol, I1.input_string, S1.seq;
The S1 and S2 copies of Sequence are used to locate bracketing pairs of
commas, and the entire set of substrings located between them is
extracted and cast as integers in one non-procedural step. The trick
is to be sure that the right hand comma of the bracketing pair is the
closest one to the first comma.
You can then write:
SELECT *
FROM Foobar
WHERE x IN (SELECT parm FROM Parmlist WHERE key_col = :something);
Of course the right way to do this would be with a base table that
holds the list, or a longer parameter list:
WHERE x IN (@.p1, COALESCE (@.p2, @.p1), .. COALESCE (@.p99, @.p1);
The reason for the Coalesce() is to guarantee you have no nulls. You
must have a value for @.p1. All the other partameters default to NULL.
Alternatively, you can have a local variable, @.p0, which is set to some
impossible value as a sentinel.|||Actually I executed
set @.param = '1,2,3'
insert into #t
exec('SELECT ' + REPLACE(@.param, ',' ' UNION ALL SELECT ') )
To give me
insert into #t
exec (select 1 union all select 2 union all select 3)
Each row produced by executing this is one row and column of the temp table.
Is that what you meant by 1NF (every field must be atomic?)
Must of explained myself badly.
Point is using this CSV param dynamically in a SP is much faster than
breaking CSV param down into a temp table/variable or using a table
returning function.
SP recompile time is not an issue. Maybe if the CSV param gets very large
then using the temp table or function may be quicker.
Point is don't like dynamic SQL but this time forced to.
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1112318927.848861.167290@.g14g2000cwa.googlegroups.com...
> Ever hear about First Normal Form (1NF)?
> Pardon the fact that this "cut & paste" is in Standard SQL and not
> dialect. Passing a list of parmeters to a stored procedure can be done
> by putting them into a string with a separator. I like to use the
> traditional comma. Let's assume that you have a whole table full of
> such parameter lists:
> CREATE TABLE InputStrings
> (keycol CHAR(10) NOT NULL PRIMARY KEY,
> input_string VARCHAR(255) NOT NULL);
> INSERT INTO InputStrings VALUES ('first', '12,34,567,896');
> INSERT INTO InputStrings VALUES ('second', '312,534,997,896');
> ...
> This will be the table that gets the outputs, in the form of the
> original key column and one parameter per row.
> CREATE TABLE Parmlist
> (keycol CHAR(10) NOT NULL PRIMARY KEY,
> parm INTEGER NOT NULL);
> It makes life easier if the lists in the input strings start and end
> with a comma. You will need a table of sequential numbers -- a
> standard SQL programming trick, Now, the real query, in SQL-92 syntax:
>
> INSERT INTO ParmList (keycol, parm)
> SELECT keycol,
> CAST (SUBSTRING (I1.input_string
> FROM S1.seq
> FOR MIN(S2.seq) - S1.seq -1)
> AS INTEGER)
> FROM InputStrings AS I1, Sequence AS S1, Sequence AS S2
> WHERE SUBSTRING ( ',' || I1.input_string || ',' FROM S1.seq FOR 1) =
> ','
> AND SUBSTRING (',' || I1.input_string || ',' FROM S2.seq FOR 1) =
> ','
> AND S1.seq < S2.seq
> GROUP BY I1.keycol, I1.input_string, S1.seq;
> The S1 and S2 copies of Sequence are used to locate bracketing pairs of
> commas, and the entire set of substrings located between them is
> extracted and cast as integers in one non-procedural step. The trick
> is to be sure that the right hand comma of the bracketing pair is the
> closest one to the first comma.
> You can then write:
> SELECT *
> FROM Foobar
> WHERE x IN (SELECT parm FROM Parmlist WHERE key_col = :something);
> Of course the right way to do this would be with a base table that
> holds the list, or a longer parameter list:
> WHERE x IN (@.p1, COALESCE (@.p2, @.p1), .. COALESCE (@.p99, @.p1);
> The reason for the Coalesce() is to guarantee you have no nulls. You
> must have a value for @.p1. All the other partameters default to NULL.
> Alternatively, you can have a local variable, @.p0, which is set to some
> impossible value as a sentinel.
>|||Yitzak wrote:
> Hi I have a stored proc -
> takes a long time to execute so re-compilation isn't an issue.
> I pass a comma separated varchar param to the stored procedure.
> exec sp_somename @.CSV = '1,2,3'
>
> If I build the SQL statement in the SP and then execute the statement
> dynamically:
> EXEC ('SELECT * FROM table1, ... other tables WHERE ID IN (1,2,3,4)
> ...rest of sql'
>
You have several options, which are explained at
http://www.sommarskog.se/arrays-in-sql.html
--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"|||Thanks
Tried different options all better than dynamic SQL (maintenance,
debugging, security) - essentially all use a table to join.
This in my cases is always double the speed of the similar Dynamic SQL.
Recompilation ain't an issue on a SP that takes 40secs to run..
Can't understand as I thought MSSQL turned a "Select IN" into a join on temp
table, but creating my own indexed temp table/variable from SP or Function
takes twice teh time of "SELECT IN"
"Bob Barrows [MVP]" <reb01501@.NOyahoo.SPAMcom> wrote in message
news:#EOF$xwNFHA.2252@.TK2MSFTNGP15.phx.gbl...
> Yitzak wrote:
> You have several options, which are explained at
> http://www.sommarskog.se/arrays-in-sql.html
> --
> Microsoft MVP - ASP/ASP.NET
> Please reply to the newsgroup. This email account is my spam trap so I
> don't check it very often. If you must reply off-line, then remove the
> "NO SPAM"
>