Sunday, March 25, 2012
Calling sp in an expression
Is it possible to call a stored procedure (or a dataset that is based on an
sp) from the expression property in a report?
Can the "Code" tab be used to call the stored procedure and that "code" be
referred to from the expression property in a report (if the above is not
possible)?
This is what I am doing (or want to do):
I have a custom assembly that I don't want to put in the
MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to be in the
folder of my choice and under my control since the folder structure of
Microsoft for SQL Server 2005 (CTP July version) has changed.
So I created an Assembly in SQL Server 2005 by referring to this DLL. I
created a stored procedure that calls the assembly. Now I want to call this
stored procedure from the expression property of the report since I will be
passing the arguments from here.
Any help is appreciated. Thanks.No. The only place that a stored procedure can be called (unless you use a
custom assembly which is what you are trying to get away from) from is by
creating a dataset. The dataset query parameter mapping can use an
expression. If you have just a single record coming back then you can use
First aggregate to refer to it in your report. I do this all the time. Not
sure if that solves your problem or not.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:4626D487-0E50-4F89-892C-59D33DB800C3@.microsoft.com...
> Hi All,
> Is it possible to call a stored procedure (or a dataset that is based on
> an
> sp) from the expression property in a report?
> Can the "Code" tab be used to call the stored procedure and that "code" be
> referred to from the expression property in a report (if the above is not
> possible)?
> This is what I am doing (or want to do):
> I have a custom assembly that I don't want to put in the
> MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to be in
> the
> folder of my choice and under my control since the folder structure of
> Microsoft for SQL Server 2005 (CTP July version) has changed.
> So I created an Assembly in SQL Server 2005 by referring to this DLL. I
> created a stored procedure that calls the assembly. Now I want to call
> this
> stored procedure from the expression property of the report since I will
> be
> passing the arguments from here.
> Any help is appreciated. Thanks.|||Thanks for you prompt reply.
Can you please explain with an example - may be this will work.
"Bruce L-C [MVP]" wrote:
> No. The only place that a stored procedure can be called (unless you use a
> custom assembly which is what you are trying to get away from) from is by
> creating a dataset. The dataset query parameter mapping can use an
> expression. If you have just a single record coming back then you can use
> First aggregate to refer to it in your report. I do this all the time. Not
> sure if that solves your problem or not.
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> news:4626D487-0E50-4F89-892C-59D33DB800C3@.microsoft.com...
> > Hi All,
> > Is it possible to call a stored procedure (or a dataset that is based on
> > an
> > sp) from the expression property in a report?
> >
> > Can the "Code" tab be used to call the stored procedure and that "code" be
> > referred to from the expression property in a report (if the above is not
> > possible)?
> >
> > This is what I am doing (or want to do):
> > I have a custom assembly that I don't want to put in the
> > MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to be in
> > the
> > folder of my choice and under my control since the folder structure of
> > Microsoft for SQL Server 2005 (CTP July version) has changed.
> >
> > So I created an Assembly in SQL Server 2005 by referring to this DLL. I
> > created a stored procedure that calls the assembly. Now I want to call
> > this
> > stored procedure from the expression property of the report since I will
> > be
> > passing the arguments from here.
> >
> > Any help is appreciated. Thanks.
>
>|||Which part is confusing to you? Mapping a query parameter to an expression?
Using the First aggragate?
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:1C743F5A-368F-4F98-9EC5-42FA3F8860CB@.microsoft.com...
> Thanks for you prompt reply.
> Can you please explain with an example - may be this will work.
> "Bruce L-C [MVP]" wrote:
>> No. The only place that a stored procedure can be called (unless you use
>> a
>> custom assembly which is what you are trying to get away from) from is by
>> creating a dataset. The dataset query parameter mapping can use an
>> expression. If you have just a single record coming back then you can use
>> First aggregate to refer to it in your report. I do this all the time.
>> Not
>> sure if that solves your problem or not.
>>
>> --
>> Bruce Loehle-Conger
>> MVP SQL Server Reporting Services
>> "KMP" <KMP@.discussions.microsoft.com> wrote in message
>> news:4626D487-0E50-4F89-892C-59D33DB800C3@.microsoft.com...
>> > Hi All,
>> > Is it possible to call a stored procedure (or a dataset that is based
>> > on
>> > an
>> > sp) from the expression property in a report?
>> >
>> > Can the "Code" tab be used to call the stored procedure and that "code"
>> > be
>> > referred to from the expression property in a report (if the above is
>> > not
>> > possible)?
>> >
>> > This is what I am doing (or want to do):
>> > I have a custom assembly that I don't want to put in the
>> > MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to be
>> > in
>> > the
>> > folder of my choice and under my control since the folder structure of
>> > Microsoft for SQL Server 2005 (CTP July version) has changed.
>> >
>> > So I created an Assembly in SQL Server 2005 by referring to this DLL. I
>> > created a stored procedure that calls the assembly. Now I want to call
>> > this
>> > stored procedure from the expression property of the report since I
>> > will
>> > be
>> > passing the arguments from here.
>> >
>> > Any help is appreciated. Thanks.
>>|||Mapping a query parameter to an expression.
"Bruce L-C [MVP]" wrote:
> Which part is confusing to you? Mapping a query parameter to an expression?
> Using the First aggragate?
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> news:1C743F5A-368F-4F98-9EC5-42FA3F8860CB@.microsoft.com...
> > Thanks for you prompt reply.
> >
> > Can you please explain with an example - may be this will work.
> >
> > "Bruce L-C [MVP]" wrote:
> >
> >> No. The only place that a stored procedure can be called (unless you use
> >> a
> >> custom assembly which is what you are trying to get away from) from is by
> >> creating a dataset. The dataset query parameter mapping can use an
> >> expression. If you have just a single record coming back then you can use
> >> First aggregate to refer to it in your report. I do this all the time.
> >> Not
> >> sure if that solves your problem or not.
> >>
> >>
> >> --
> >> Bruce Loehle-Conger
> >> MVP SQL Server Reporting Services
> >>
> >> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> >> news:4626D487-0E50-4F89-892C-59D33DB800C3@.microsoft.com...
> >> > Hi All,
> >> > Is it possible to call a stored procedure (or a dataset that is based
> >> > on
> >> > an
> >> > sp) from the expression property in a report?
> >> >
> >> > Can the "Code" tab be used to call the stored procedure and that "code"
> >> > be
> >> > referred to from the expression property in a report (if the above is
> >> > not
> >> > possible)?
> >> >
> >> > This is what I am doing (or want to do):
> >> > I have a custom assembly that I don't want to put in the
> >> > MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to be
> >> > in
> >> > the
> >> > folder of my choice and under my control since the folder structure of
> >> > Microsoft for SQL Server 2005 (CTP July version) has changed.
> >> >
> >> > So I created an Assembly in SQL Server 2005 by referring to this DLL. I
> >> > created a stored procedure that calls the assembly. Now I want to call
> >> > this
> >> > stored procedure from the expression property of the report since I
> >> > will
> >> > be
> >> > passing the arguments from here.
> >> >
> >> > Any help is appreciated. Thanks.
> >>
> >>
> >>
>
>|||RS makes this concept murky because it automatically creates a Report
Parameter for every query parameter. However, you can map query parameters
to the same report parameter or to an expression. For instance, let's say I
have two datasets, they both need from and to dates. Let's further say that
the query parameters are named differently. For instance @.FromDate and
@.StartDate. Reporting services will create two report parameters. However
you can map both @.FromDate and @.StartDate to the same report parameter.
Click on the ... in the dataset tab, Parameters tab. On the left is the
query parameter on the right is what it is mapped to. That is where you
would map both to the same report parameter. OK, now, mapping to an
expression, you can click on the combo box and set expression.
For instance this calls some code behind report:
=Code.SomecodeOfMine(Parameters!Param1.Value)
This sets to the current day/time
=Now
Etc. Your expression can be pretty much anything.
When you pick expression you go to the expression builder.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:74430973-4547-419F-AFFC-29CA4CE68667@.microsoft.com...
> Mapping a query parameter to an expression.
> "Bruce L-C [MVP]" wrote:
>> Which part is confusing to you? Mapping a query parameter to an
>> expression?
>> Using the First aggragate?
>>
>> --
>> Bruce Loehle-Conger
>> MVP SQL Server Reporting Services
>> "KMP" <KMP@.discussions.microsoft.com> wrote in message
>> news:1C743F5A-368F-4F98-9EC5-42FA3F8860CB@.microsoft.com...
>> > Thanks for you prompt reply.
>> >
>> > Can you please explain with an example - may be this will work.
>> >
>> > "Bruce L-C [MVP]" wrote:
>> >
>> >> No. The only place that a stored procedure can be called (unless you
>> >> use
>> >> a
>> >> custom assembly which is what you are trying to get away from) from is
>> >> by
>> >> creating a dataset. The dataset query parameter mapping can use an
>> >> expression. If you have just a single record coming back then you can
>> >> use
>> >> First aggregate to refer to it in your report. I do this all the time.
>> >> Not
>> >> sure if that solves your problem or not.
>> >>
>> >>
>> >> --
>> >> Bruce Loehle-Conger
>> >> MVP SQL Server Reporting Services
>> >>
>> >> "KMP" <KMP@.discussions.microsoft.com> wrote in message
>> >> news:4626D487-0E50-4F89-892C-59D33DB800C3@.microsoft.com...
>> >> > Hi All,
>> >> > Is it possible to call a stored procedure (or a dataset that is
>> >> > based
>> >> > on
>> >> > an
>> >> > sp) from the expression property in a report?
>> >> >
>> >> > Can the "Code" tab be used to call the stored procedure and that
>> >> > "code"
>> >> > be
>> >> > referred to from the expression property in a report (if the above
>> >> > is
>> >> > not
>> >> > possible)?
>> >> >
>> >> > This is what I am doing (or want to do):
>> >> > I have a custom assembly that I don't want to put in the
>> >> > MsSql\ReportServer\Bin folder. I want the custom assembly (DLL) to
>> >> > be
>> >> > in
>> >> > the
>> >> > folder of my choice and under my control since the folder structure
>> >> > of
>> >> > Microsoft for SQL Server 2005 (CTP July version) has changed.
>> >> >
>> >> > So I created an Assembly in SQL Server 2005 by referring to this
>> >> > DLL. I
>> >> > created a stored procedure that calls the assembly. Now I want to
>> >> > call
>> >> > this
>> >> > stored procedure from the expression property of the report since I
>> >> > will
>> >> > be
>> >> > passing the arguments from here.
>> >> >
>> >> > Any help is appreciated. Thanks.
>> >>
>> >>
>> >>
>>
Monday, March 19, 2012
Calling a Stored Procedure to list Data
I am very new to this and would really appreciate any knowledge anyone could share.
A quick example:
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = @."Data Source=Confute;Initial Catalog=AdventureWorks;Integrated Security=SSPI";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_SearchByCategory", connection);
cmd.Parameters.Add("@.category", txtBox_Name.Text);
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
txtBox_Name.Text = dt.Rows[0][0].ToString();
}
}
Sunday, March 11, 2012
Calling a Function from a Stored Procedure
Hello all,
I'm trying to construct a select statement in a stored procedure that filters based on the returned values of a number of functions. My function works fine, but when I try to call the function from the stored procedure I get an error.
I'm going to try explain the thought process behind what I'm doing. Hope I make enough sense.
The purpose of the stored procedure is to perform a wildcard search on a tool. The tool contains a number of FK that link to different tables (e.g., manufacturer, vendor). So I'm creating functions that also search the manufacturer and vendor and return the matching IDs.
Example of tool SELECT statement:
SELECT tool_number, tool_descriptionFROM toolWHERE tool_manufacturerIN (UDFmanufacturer_SearchName(@.search_string)
This gives me an error:
'UDFmanufacturer_SearchName' is not a recognized built-in function name.
Function code (removed some wrapping code for simplicity):
SELECT manufacturer_idFROM manufacturerWHERE manufacturer_nameLIKE'%' + @.search_string +'%'
These statements both work if I run a independent query:
SELECT *FROM UDFmanufacturer_SearchName('mol')
SELECT *FROM toolWHERE tool_manufacturerIN (SELECT *FROM UDFmanufacturer_SearchName('mol'))This code fails:
SELECT *FROM ato_toolWHERE ato_tool_manufacturerIN (UDFmanufacturer_SearchName('mol'))
I'm stuck. I haven't been able to find anything that shows me where I'm going wrong. Any thoughts or suggestions are appreciated.
Thanks,
Jay
You have to use a SELECT FROM function and not directly in the IN clause. Also use the prefix "dbo." for the function and see if it helps.
SELECT *FROM toolWHERE tool_manufacturerIN (SELECT *FROMdbo.UDFmanufacturer_SearchName('mol'))|||That was it. I thought I could use the function without needing the " SELECT * " in front.
Thanks for your help.
|||The above post is absolutely correct.
UDFmanufacturer_SearchName is a table valued function (fancy for it returns a table/resultset). If you then think of UDFmanufacturer_SearchName('mol') as being a table, then
SELECT *
FROM ato_tool
WHERE ato_tool_manufacturerIN (UDFmanufacturer_SearchName('mol'))
isn't valid for the same reasons that:
SELECT *
FROM ato_tool
WHERE ato_tool_manufacturerIN (tool_manufacturer)
isn't valid.
So because tables aren't valid where you've placed it, it's looking for a different type of function, like one that returns a string, date, or number. It can't find one, so it says it can't find the function. Also, you should always prefix your function names with 'dbo.' or the correct schema. It may work without it in some places, but I believe syntactically it's wrong (sloppy). Don't be suprised if a service pack, hotfix, or the next version of SQL Server starts to fail on it.|||
Thanks for the explanation, it was helpful.
Hadn't thought about the schema prefix. Will keep it in mind.
Thanks.
Thursday, March 8, 2012
Call stored procedure within reporting service
return a result set. The DBMS is Sybase SQL Server.
Can reporting service do it?
Thanks a lot for your help.Create ODBC connection to your sybase file and
create dataset based on ODBC connection
John Wang wrote:
> I'm trying to generate a report based on a stored procedure which will
> return a result set. The DBMS is Sybase SQL Server.
> Can reporting service do it?
> Thanks a lot for your help.
Saturday, February 25, 2012
Call ALTER LOGIN
I am trying to create a stored procedure to Call ALTER LOGIN based on the the username passed in. However, the Alter login statement chokes on any parameter. Is there a way I can alter sql logins from a web form ?
I try the following and it bombs
ALTER
LOGIN @.LoginNameWITH PASSWORD= @.PasswordBut this works
ALTER LOGIN 'TestUser' WITH PASSWORD = '123test'
I guess the alter login statement does not work with Parameters.
Any thoughts ?
EXEC('ALTER LOGIN ' + @.loginName + ' WITH PASSWORD= ' + @.Passrowd)
|||
I get an error when I set the password. Should I add double quotes to the password ?
|||yes you are right. You need to escape the quotes..Sorry about that.
EXEC('ALTER LOGIN ' + @.loginName + ' WITH PASSWORD= ''' + @.Passrowd + '''')
|||Perfect Thanks!Thursday, February 16, 2012
Calculation based on total at Table footer (eg. % of report total)
I have data on a report where I am subtotalling by Items on an invoice. So,
my subtotal has the sum of all the invoices for that item.
I also want to do a calculation that will calculate for each item (that is
summarized) % of total sale for all items. Presently, my totals for all items
are in the Table Footer.
Item Amount Percent of Total
A 10 (subtotal) 10/15 =67%(ie divided by report
total)
B 5 (subtotal) 5/15 =33%
Report Total = 15
How do I do this?
Thanks
Ranjit CharlesHi,
You need to have a report variable which stores the grand total already or a
select statement which stores the grand total. Then you can use this variable
to find out the percentage. You can have a dataset created for this select
alone which will find out the grand total and use the dataset for percentage.
Regards
Amarnath
"Ranjit Charles" wrote:
> Hi!
> I have data on a report where I am subtotalling by Items on an invoice. So,
> my subtotal has the sum of all the invoices for that item.
> I also want to do a calculation that will calculate for each item (that is
> summarized) % of total sale for all items. Presently, my totals for all items
> are in the Table Footer.
> Item Amount Percent of Total
> A 10 (subtotal) 10/15 =67%(ie divided by report
> total)
> B 5 (subtotal) 5/15 =33%
> Report Total = 15
> How do I do this?
> Thanks
> Ranjit Charles|||Or you can sum the total amount and put it in to a new value field for the
select statement...
e.g. select *, (select sum() ... from ...) "GrandTotal" from ...
which obviously means you calculate the total for every line but SQL is
pretty efficient.
Craig
"Amarnath" <Amarnath@.discussions.microsoft.com> wrote in message
news:4977EB5C-C4A7-4109-B61E-F3D9B059DE28@.microsoft.com...
> Hi,
> You need to have a report variable which stores the grand total already or
> a
> select statement which stores the grand total. Then you can use this
> variable
> to find out the percentage. You can have a dataset created for this select
> alone which will find out the grand total and use the dataset for
> percentage.
> Regards
> Amarnath
>
> "Ranjit Charles" wrote:
>> Hi!
>> I have data on a report where I am subtotalling by Items on an invoice.
>> So,
>> my subtotal has the sum of all the invoices for that item.
>> I also want to do a calculation that will calculate for each item (that
>> is
>> summarized) % of total sale for all items. Presently, my totals for all
>> items
>> are in the Table Footer.
>> Item Amount Percent of Total
>> A 10 (subtotal) 10/15 =67%(ie divided by report
>> total)
>> B 5 (subtotal) 5/15 =33%
>> Report Total = 15
>> How do I do this?
>> Thanks
>> Ranjit Charles
Calculating Trends
I am looking for the most efficient way to calculate a trend based upon
individual figures in a table. Here is an example (e.g. sold items):
Data:
date number
-- --
2001-01-01 3
2001-01-02 5
2001-01-03 10
expected result:
date totsl number of sold items
-- --
2001-01-01 3
2001-01-02 8
2001-01-03 18
Any idea hoe I can solve that with the best performance possible?
ThanksOn Thu, 2 Jun 2005 22:36:17 +0200, CrazyHorse wrote:
> Hello,
> I am looking for the most efficient way to calculate a trend based upon
> individual figures in a table. Here is an example (e.g. sold items):
> Data:
> date number
> -- --
> 2001-01-01 3
> 2001-01-02 5
> 2001-01-03 10
> expected result:
> date totsl number of sold items
> -- --
> 2001-01-01 3
> 2001-01-02 8
> 2001-01-03 18
> Any idea hoe I can solve that with the best performance possible?
> Thanks
"Calculating Running Totals"
http://www.sqlteam.com/item.asp?ItemID=3856
Summary: Depending on the size of your data, this is one instance where a
cursor may actually be worth using. This is because the cursor will only
make one pass through the table, while any set-based solution has to join
the table with itself - which can produce millions of temporary rows, at
least momentarily.
Most of the time, an even better idea is to let the SQL side just retrieve
the un-summarized data, and let the consuming application produce the
running total. In effect, this is moving the cursor from the database side
to the client side.|||Do:
SELECT dt, ( SELECT SUM( number )
FROM tbl t2
WHERE t2.dt <= t1.dt )
FROM tbl t1 ;
Anith|||Hello,
thanks for your help.
<CrazyHorse> wrote in message news:uvjo$K7ZFHA.2984@.TK2MSFTNGP15.phx.gbl...
> Hello,
> I am looking for the most efficient way to calculate a trend based upon
> individual figures in a table. Here is an example (e.g. sold items):
> Data:
> date number
> -- --
> 2001-01-01 3
> 2001-01-02 5
> 2001-01-03 10
> expected result:
> date totsl number of sold items
> -- --
> 2001-01-01 3
> 2001-01-02 8
> 2001-01-03 18
> Any idea hoe I can solve that with the best performance possible?
> Thanks
>
Tuesday, February 14, 2012
calculating load
can someone suggest me something based on the following parameters given
Q1 How many transactions are expected during the peak hour of activity? How
many transactions are expected each business day?
ANS: 300 concurrent users (max) will connect to application server and based
on the activity application server will call stored procedure stored in the
database server (one at a time). Most of the stored procedure (approx 500)
has single SELECT/UPDATE statement but, around 100 procedures has multiple
SELECT/UPDATE statement inside them (max 8 statement), frequency of calling
these procedures are less compared to the other 500.
Q2 How many database connections are required? From Appln to DB
ANS: How can we check that, will SQL profiler be able to give me this info?
Q3 How much storage should be reserved for the database (data and indexes)?
15 GB of database size is expected.
Q4 Can your application support 2 appln servers talking to one db at back en
d?
ANS: Yes"NewTOPROJECT" <NewTOPROJECT@.discussions.microsoft.com> wrote in message
news:3DF1EF15-D256-4961-881E-68427A184A0B@.microsoft.com...
> SEVRER WORKLOAD PARAMETERS:
> can someone suggest me something based on the following parameters given
>
I suggest you test, there's not nearly enough information to accruately size
the hardware. By the way, no matter how detailed your questionare is, you
will still need to test.
That workload does not appear to be too extreme. 15GB is on the large size
for an OLTP application, and a big wildcard is how expensive your SELECT
statements are. With 15GB of data there is ample opportunity to create very
expensive queries. On the other hand, if the data is largly historical and
you don't do historical reporting during peak load times, your workload may
be quite light.
So throw the profiler on it and watch the Reads and the CPU. The most
expensive 10% of queries may use 90% of your resources, so identify and
optimize these.
David
calculating load
can someone suggest me something based on the following parameters given
Q1 How many transactions are expected during the peak hour of activity? How
many transactions are expected each business day?
ANS: 300 concurrent users (max) will connect to application server and based
on the activity application server will call stored procedure stored in the
database server (one at a time). Most of the stored procedure (approx 500)
has single SELECT/UPDATE statement but, around 100 procedures has multiple
SELECT/UPDATE statement inside them (max 8 statement), frequency of calling
these procedures are less compared to the other 500.
Q2 How many database connections are required? From Appln to DB
ANS: How can we check that, will SQL profiler be able to give me this info?
Q3 How much storage should be reserved for the database (data and indexes)?
15 GB of database size is expected.
Q4 Can your application support 2 appln servers talking to one db at back end?
ANS: Yes"NewTOPROJECT" <NewTOPROJECT@.discussions.microsoft.com> wrote in message
news:3DF1EF15-D256-4961-881E-68427A184A0B@.microsoft.com...
> SEVRER WORKLOAD PARAMETERS:
> can someone suggest me something based on the following parameters given
>
I suggest you test, there's not nearly enough information to accruately size
the hardware. By the way, no matter how detailed your questionare is, you
will still need to test.
That workload does not appear to be too extreme. 15GB is on the large size
for an OLTP application, and a big wildcard is how expensive your SELECT
statements are. With 15GB of data there is ample opportunity to create very
expensive queries. On the other hand, if the data is largly historical and
you don't do historical reporting during peak load times, your workload may
be quite light.
So throw the profiler on it and watch the Reads and the CPU. The most
expensive 10% of queries may use 90% of your resources, so identify and
optimize these.
David
calculating load
can someone suggest me something based on the following parameters given
Q1 How many transactions are expected during the peak hour of activity? How
many transactions are expected each business day?
ANS: 300 concurrent users (max) will connect to application server and based
on the activity application server will call stored procedure stored in the
database server (one at a time). Most of the stored procedure (approx 500)
has single SELECT/UPDATE statement but, around 100 procedures has multiple
SELECT/UPDATE statement inside them (max 8 statement), frequency of calling
these procedures are less compared to the other 500.
Q2 How many database connections are required? From Appln to DB
ANS: How can we check that, will SQL profiler be able to give me this info?
Q3 How much storage should be reserved for the database (data and indexes)?
15 GB of database size is expected.
Q4 Can your application support 2 appln servers talking to one db at back end?
ANS: Yes
"NewTOPROJECT" <NewTOPROJECT@.discussions.microsoft.com> wrote in message
news:3DF1EF15-D256-4961-881E-68427A184A0B@.microsoft.com...
> SEVRER WORKLOAD PARAMETERS:
> can someone suggest me something based on the following parameters given
>
I suggest you test, there's not nearly enough information to accruately size
the hardware. By the way, no matter how detailed your questionare is, you
will still need to test.
That workload does not appear to be too extreme. 15GB is on the large size
for an OLTP application, and a big wildcard is how expensive your SELECT
statements are. With 15GB of data there is ample opportunity to create very
expensive queries. On the other hand, if the data is largly historical and
you don't do historical reporting during peak load times, your workload may
be quite light.
So throw the profiler on it and watch the Reads and the CPU. The most
expensive 10% of queries may use 90% of your resources, so identify and
optimize these.
David
Calculating Length of Service Categories based on Start Dates
Basically, I have the following table structure
Employee(employee_number, continuous_start_date, ...)
The problem lies in working out a summary of service categories (0-6months, 7-12months, 13-24, 25+).
I can work out the length of service in months with the following code
SELECT DateDiff(mm, continuous_start_date, GetDate()) AS 'Service in months'
FROM employee
So the first stage is to summarise the length of service into groups as mentioned above.
Then the final stage is working out how many people are in each group!
Hope I have given enough information - and please do not post a full solution - just some hints on how to get the desired result ;)
Thanks later, and in advance :p
-GeorgeVHi George
I would create a table with upper and lower month limits for each of the bands, and proobably a name for each band. Create an join to this table on your calculated "monthsInService" field using the between operator.
Robert would then be your mothers brother.|||Nice suggestion Poots, but I'm aiming to get this in a single query (so, CASE statements, or an array-type thing?) :p
I am struggling with getting the results into groups at the moment - I've kind hit a brick wall - wondering if it's quicker to climb, go under, walk round, etc :p Not sure what's the best way to my destination (or if it even is!)|||My suggestion works fine as a sinlge statement. Why wouldn't it?
Reasons not to use a case statement:
http://weblogs.sqlteam.com/jeffs/archive/2006/02/10/9002.aspx|||Hmm, you make a good point!
So, let's asy I make a table ServiceCategory(Unique_Identifier, Lower_Limit, Upper_Limit, Limit_Description (and possibly Sort_Order?))
Would I join to my table like this:
FROM Employee e
INNER JOIN ServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
Apologies, I'm trying to get the logic right before creating a new table (they don't really like people creating new tables - hence my single query approach)
Thanks Poots :)|||Yes.
Personally I wouldn't bother with a surrogate key because I can't see it ever serving any purpose. But that's just me - a minor matter. :)
I presume you are comfy with the sums part?|||BTW - I presume there is no end of service date in the table? If not you will need to account for that in your expression...|||two stars for poots on this thread -- one for suggesting the join to a range table, and another for advising against the surrogate key
nice job
:)|||Thank you Rudy. Makes up for the couple of cock ups I made in the last SQL threads we shared in common :)|||Surrogate key is automatically generated by our HR system, I know it's not needed ;) But still, good catch!
As for the sums bit - I'll have to get back to you after I've played some more - thanks for the suggestions, going to ask (yes, sadly I have to ask when I'm playing with the HR system... :s) to create my new table now :)|||Ah - I see. You can develop this using a table variable until you are happy it works great then submit the create table script to them once you are 100% confident.|||Table variable?
And I have still never written a create table script - I have only ever used Enterprise Manager (HR system is on 2K)...
This might give me an oppurtunity to have a go - I'll be back with an attempt soon ;)|||This is a template I use. Find & replace the placeholders. See if it helps:
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N't_name') BEGIN
DROP TABLE dbo.t_name
END
CREATE TABLE dbo.t_name
(
c_name INT NOT NULL CONSTRAINT df_t_name_c_name DEFAULT 0
, CONSTRAINT pk_t_name PRIMARY KEY CLUSTERED (c_name) WITH (FILLFACTOR = 80)
, CONSTRAINT ix_t_name_c_name_u_nc UNIQUE NONCLUSTERED (c_name) WITH (FILLFACTOR = 80)
, CONSTRAINT ck_t_name_c_name CHECK (c_name BETWEEN 1 AND 10)
, CONSTRAINT fk_t_name_other_t_name FOREIGN KEY (c_name) REFERENCES other_t_name (c_name) ON DELETE CASCADE
)
GO|||How's this for an attempt? :)
CREATE TABLE ServiceCategory
(
Lower_Limit numeric,
Upper_Limit numeric,
Limit_Description char(16),
Sort_Order numeric
)
INSERT
INTO ServiceCategory(Lower_Limit, Upper_Limit, Limit_Description, Sort_Order)
VALUES (0, 6, '0 to 6 months', 1)
SELECT *
FROM ServiceCategory|||Oh and my full solution:
SELECT Count(s.Limit_Description) AS 'Total'
,s.Limit_Description
FROM pwa_master.Employee e
INNER JOIN ServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Limit_Description, s.Sort_Order
ORDER
BY s.Sort_Order
Thank you :D|||That's fine. Not so sure about the description now (none key column dependancies - maybe I am just a fuss pot). I think TINYINT is probably sufficient - numeric is a bit overkill. Inner join removes anyone not accounted for in the range table. There is no end date right? Add some NOT NULLS into your table definition (all columns).
All the above is picky - good job.|||Hmm, well it did suddenly occur to me that there are a whole 3 null values in the system (which slipped through the net before the field was made mandatory...) but if I flag them up to HR it will be dealt with ;)
As for my top range, not sure what to put, I currently have a rediculous value of 1200 (100 years service... yeah, right ;))
So this covers everyone (other than the three silly nulls from above)... It's not pretty, but it works... Suggestions welcomed with open arms! :)
Should I drop the desc, just not sure what to do instead (want to be able to display a description of each range)... Hmm...|||I think a "forever" date is ok in this instance.
I might just be being too picky re your desciption field. The problem of course is second normal form and if you end up changing your bands. If you drop the desc you can create a view something like:
SELECT
Lower_Limit, Upper_Limit,
CAST(Lower_Limit AS VARCHAR()) + ' to ' + CAST(Upper_Limit AS VARCHAR()) + ' months' AS Limit_Description,Sort_Order
FROM dbo.ServiceCategory
HTH|||I tried that, but was getting conversion errors... Was thinking of Cast/convert statements as a fix :D (I was actually really close!)
I like being picky, so I want to also sort out my "forever" limit, as you put it, but I'm not exactly sure how...|||Nah - an absurdly high value in there is fine. That is what I would do. You could leave it null and then use COALESCE() in your join but I prefer having a value in there myself since there is no time when you will want it to count as a NULL.
I'll ask one last time (maybe you have spotted this and didn't bother answering) - are there leaving dates in the staff table? If not then I presume it is current staff only?
None of you lower limits are the same as your upper limits are they? (for example row two does not start at 6 but at 7).|||SELECT Limit_Description
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM ServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM ServiceCategory
:cool: hehe|||Employee table is a view on the people table, based on termination date being empty/null/blank/etc. (EDIT: and the continuous_start_date being greater than or equal to today)
As for my limits:
0 6
7 12
13 24
25 60
61 1200|||Looks to me that you are all sorted then :)|||Yippee :D
Now I have to make this into a sproc written in FoxPro and I'm done ;)
Roll on our new HR system!
Thanks for all your help mate :beer:|||Ooh, one little thing while I'm here:
ALTER TABLE ServiceCategory DROP COLUMN Limit_Description
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'Limit_Description'.
Any ideas? I'm completely stumped here...|||Annoyingly, the keyword COLUMN in this case causes an error. ALTER TABLE DROP... always drops a column - no need for the key word.|||I don't think I follow - I've tried:
ALTER TABLE ServiceCategory DROP Limit_Description
Which causes errors, "not a constraint"...
ALTER TABLE DROP ServiceCategory.Limit_Description
More errors...
*eek*|||Beg your pardon - I'm thinking of add :rolleyes:
Something wot I wrote for our more junior developers:
USE tempdb
go
BEGIN TRAN
--SET UP----------------
--Make sure the db is clean
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me') BEGIN
DROP TABLE dbo.delete_me
END
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me_too') BEGIN
DROP TABLE dbo.delete_me_too
END
--This table is pretty irrelevent - just used for a foreign key constraint example.
--If it did not exist the code would error.
CREATE TABLE dbo.delete_me_too
(
my_other_col VARCHAR(10)
, CONSTRAINT pk_delete_me_too PRIMARY KEY CLUSTERED (my_other_col) WITH (FILLFACTOR = 80)
)
GO
--This is the table we will alter.
CREATE TABLE dbo.delete_me
(
my_col INT
)
GO
--SET UP----------------
--COLUMNS----------------
--Add a column. NOTE - no COLUMN key word.
ALTER TABLE dbo.delete_me
ADD my_new_col VARCHAR(10)
--remove a colimn
ALTER TABLE dbo.delete_me
DROP COLUMN my_new_col
--Alter a column
ALTER TABLE dbo.delete_me
ALTER COLUMN my_col VARCHAR(10) NOT NULL
Go
--COLUMNS----------------
--CONSTRAINTS----------------
--Add a primary key
ALTER TABLE dbo.delete_me
ADD CONSTRAINT pk_delete_me PRIMARY KEY CLUSTERED (my_col) WITH (FILLFACTOR = 80)
--Add a unique constraint (note - a unique constraint is enforced as an index so you can
--either add a unique constraint or create a unique index.
ALTER TABLE dbo.delete_me
ADD CONSTRAINT ix_delete_me_my_col_u_nc UNIQUE NONCLUSTERED (my_col) WITH (FILLFACTOR = 80)
--Add a check constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT ck_delete_me_my_col CHECK (my_col NOT LIKE '%[0-9]%')
--Add a foreign key constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT fk_delete_me_delete_me_too FOREIGN KEY (my_col) REFERENCES delete_me_too (my_other_col) ON DELETE CASCADE
--Add a default constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT df_delete_me_my_col DEFAULT 'default val' FOR my_col
--NOTE - there is no ALTER constraint syntax. You must drop the constraint and then
--add the constraint with the new settings. You can, however, user ALTER INDEX syntax
--for changing indexes. Check BoL for ALTER INDEX for more information.
--Drop the constraints. NOTE - the syntax is the same for all of them.
--You don't *have* to use the CONSTRAINT key word when dropping constraints.
ALTER TABLE dbo.delete_me
DROP CONSTRAINT df_delete_me_my_col
ALTER TABLE dbo.delete_me
DROP fk_delete_me_delete_me_too
ALTER TABLE dbo.delete_me
DROP ck_delete_me_my_col
ALTER TABLE dbo.delete_me
DROP CONSTRAINT ix_delete_me_my_col_u_nc
ALTER TABLE dbo.delete_me
DROP CONSTRAINT pk_delete_me
--CONSTRAINTS----------------
--Clean up
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me') BEGIN
DROP TABLE dbo.delete_me
END
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me_too') BEGIN
DROP TABLE dbo.delete_me_too
END
ROLLBACK TRAN|||--remove a colimn
ALTER TABLE dbo.delete_me
DROP COLUMN my_new_col
Why won't this work :(|||You mean the code I posted does not work? Execute the whole thing I posted - it should work fine.|||What I meant was: Your syntax matched my syntax... and mine didn't work
*confused*|||Almost but not quite.
Qualify your table name with the schema.
Check there is nothing after the statement.
Double check you have spelt the table and column names correctly.
Check you are executing in the right database.|||You may also want to check if the column to be dropped is not in any FK relationships (the heartbreak would be too much for the database, you know), check constraint, computed columns, indexes, glee clubs, etc..|||Just came back here to reference some code
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N't_name') BEGIN
DROP TABLE dbo.t_name
END
But when I run
SELECT NULL FROM sys.tables WHERE name = N'tServiceCategory'
I get:
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'sys.tables'.
Any ideas?|||i will never understand why people write a script that says "if this thing exists, drop this thing"
duh, just drop it
if it existed, then it won't exist after you drop it
and if it didn't exist, it still won't
easy-peasy
:cool:|||Ah, but when I run the SQl in FoxPro I get an error, which means I must have a logical test to see if it's there or not. But then again, the temp table idea has pretty much gone out the window thanks to Sir Poots (thanks!) it was just a matter of intrigue ;)|||i will never understand why people write a script that says "if this thing exists, drop this thing"
duh, just drop it
if it existed, then it won't exist after you drop it
and if it didn't exist, it still won't
easy-peasy
:cool:... but it causes an error.
sys.tables is a SQL 2005 thing. You need... erm...
...
dbo.sysobjects ...
where type = N'U'
...
if memory serves|||*tips cap* thank you kindly sir.
your memory is correct :)|||Reasons not to use a case statement:
http://weblogs.sqlteam.com/jeffs/archive/2006/02/10/9002.aspx
Thx Mr Flump :)
This was so helpful and informative, it's kept me out of the forum for 2 days.
I've redisgned 4 tables so far.|||... but it causes an error. which you ignore
allow me to illustrate:
you: please drop table such-and-such
database: yes sir
you: now please create table such-and-such
database: yes sir
you: please drop table such-and-such
database: but table such-and-such doesn't exist!!! oh, woe!!!!
you: now please create table such-and-such
database: yes sir|||that tactic is fine for one-offs, but if you are automating script execution in a production environment, you don't want to have to dig through a bunch of false alarms to see if something failed. I don't anyway.|||but it isn't a "failure"
what, you can't write a procedure with try/catch logic in sql server? and choose to ignore?you should be able to write a stored proc to do pretty much whatever you want, including ignoring a message when you know it can be ignored
and a proc is the only thing that i would allow in production
if i were a dba, that is ;)|||but it isn't a "failure"
what, you can't write a procedure with try/catch logic in sql server? and choose to ignore?you should be able to write a stored proc to do pretty much whatever you want, including ignoring a message when you know it can be ignored
and a proc is the only thing that i would allow in production
if i were a dba, that is ;)
try/catch doesn't cut it, because then you'd have to filter out the errors you choose to ignore (the "object doesn't exist" error in this case) and let the others bubble up. much easier to check if it exists before dropping.
frankly I'm surprised you suggested this. using try/catch as a flow control mechanism is bad form. I don't know about sql, but on other languages it's a very expensive way to do things. catching an exception isn't cheap in C++ and C#. Exceptions should be exceptional, not the rule. That's why they are called exceptions.|||which you ignore
allow me to illustrate:
you: please drop table such-and-such
database: yes sir
you: now please create table such-and-such
database: yes sir
you: please drop table such-and-such
database: but table such-and-such doesn't exist!!! oh, woe!!!!
you: now please create table such-and-such
database: yes sirBut the red text is so unaesthetically pleasing :)
Seriously though - the suggestion of TRY ... CATCH is really just another flavour of the same solution. You need one TRY ... CATCH per object because you can't have the code skip the dropping of other objects after the first execption. The only way I could see your suggestion working without it being at least as verbose as an existance check is if SQL had the equivelent of ON ERROR RESUME NEXT - which is of course the spawn of the devil(http://weblogs.sqlteam.com/jeffs/archive/2006/06/06/10093.aspx) ;)
I don't share Jezamine's philosophical objections to using TRY ... CATCH. I'm not too fussed about efficiency with schema creation scripts and I don't have a big problem with handling errors rather than avoiding them if it makes sense to do so. EDIT: in fact you might remember a question I posted regarding a similar issue a few years back when I asked for advice on the check for existence of a record before inserting Vs insert anyway and ignore the primary key violation. I just don't see the advantage of your method over checking if it exists.
I also might add that I have a load of snippets in SQLPrompt that I can call up with a couple of key strokes so I don't even have to spend extra time typing :D|||Thx Mr Flump :)
This was so helpful and informative, it's kept me out of the forum for 2 days.
I've redisgned 4 tables so far.Thanks I... copied and pasted the link myself you know. Here is another one from my extensive library:
http://www.sqljunkies.com/WebLog/amachanic/archive/2006/02/16/18123.aspx|||I'm afraid I disagree with your methods Rudy...
Ignoring errors sounds like a real bad habit to me!
In this instance I couldn't have done that anyway - what with the 3rd party interface to come - it sees an error and it cries.
Even saying that, when I was using query analyzer it hated the fact that my tables didn't exist when it tried to drop them - the last thing you need is for a user to get scared because an error occurs - just means more support calls for me to deal with "No dear, that error doesn't matter" is not what they want to hear, and leads them to think other problems are less severe also.
Rhubar, rhubarb, rhubarb...
Where was I? Oh yeah, the extra 2 lines of code are nothing compared to the amount of hassle that is produced from leaving them out.|||Hi, this post is very informative; however I would like some specific information. If someone can help me then please send me a private message. Best Regards,|||Hi, this post is very informative; however I would like some specific information. If someone can help me then please send me a private message. Best Regards,
Hi shahzadmasih,
Why not ask your question here, so we can all continue to benefit?
Mark|||As above...
This is a public forum - why not share your questions with everyone? :)|||Speaking for this shop, we prefer having the "if exists then drop" syntax for two reasons:
1) We have recently begun employing a group of offshore folks to do the actual running of the scripts. Having fewer errors for them to deal with makes their life (and consequently ours) easier.
2) We are debating going to an automatic script deployment system. If we do that, all errors would have to be caught, and probably inspected, evaluated, and a some pages of documentation sent to the end user detailing why the deployment got mucked up halfway through the deployment.
Still, if you are sitting at the console and doing this yourself, with no other people looking over your shoulder, then the "if exists then drop" syntax is perfectly valid. It is just when you have to deal with a range of skills that it becomes a problem.|||2) We are debating going to an automatic script deployment system. If we do that, all errors would have to be caught, and probably inspected, evaluated, and a some pages of documentation sent to the end user detailing why the deployment got mucked up halfway through the deployment.
that's exactly the kind of thing I meant in my earlier post by "automating script execution in a production environment".
Throwing errors unnecessarily, or using TRY/CATCH to eat them, would be a disaster for such a system.
Sunday, February 12, 2012
Calculating distance based on latitude and longitude
I need to be able to take the latitude and logitude of two locations and compare then to determine the number of miles between each point. It doesn't need to account for elevation, but assumes a flat plane with lat and long.
Does anyone have any algorithms in T-SQL to do this?
if this were easy to do, esri/mapinfo wouldn't charge big bucks for their GIS libraries. People get PhD's in geodesia!
Now, there is a solution.
Search your registry for MapX. MapInfo's MapX ocx is distributed in a few different software packages. I thought it came in Microsoft Office. But I see it also comes in Crystal XI.
Discussion about the usage of this library is not appropriate for this forum and I would direct you to Mapinfo.com.
I would be more than happy to develop a wrapper for you if you are willing to pay. I charge US$150 an hour for GIS development. probably looking at 3 hours.
|||The SQL Server 2005 Samples download contains the source
for the Spatial Data Library which I believe has
a C# function for calculating the distance between two
points from their lat/lons.
|||
it appears there is one in the SQL class. result is in Arc Minutes.
should be ok for small distances, and not near the equator. it doesn't take into account 'equatorial bulge'
in most applications it should be okay, just be aware of its propensity for error.
the algorithm doesnt look that hard to translate to straight T-SQL for increased speed:
CREATE FUNCTION CARTESIAN_PI() RETURNS DECIMAL(36, 35)
AS
BEGIN
RETURN 3.14159265358979323846264338327950288
END
GO
CREATE FUNCTION DBO.CARTESIAN_EPSILON() RETURNS DECIMAL(15,15)
AS
BEGIN
RETURN 0.000000000000001
END
GO
CREATE TYPE LATLONGUNIT FROM DECIMAL(26, 20);
GO
CREATE FUNCTION CARTESIAN_COS(@.arg LATLONGUNIT) RETURNS REAL
AS
BEGIN
DECLARE @.result REAL;
IF ABS(@.ARG-DBO.CARTESIAN_PI()) < DBO.CARTESIAN_EPSILON()
SET @.RESULT = 0
ELSE
SET @.RESULT = COS(@.arg)
RETURN @.result;
END
GO
CREATE FUNCTION DistanceLatLon(@.lat1 LATLONGUNIT, @.lon1 LATLONGUNIT, @.lat2 LATLONGUNIT, @.lon2 LATLONGUNIT) RETURNS REAL
AS
BEGIN
DECLARE @.d2r REAL
DECLARE @.nx1 REAL
DECLARE @.ny1 REAL
DECLARE @.nz1 REAL
DECLARE @.nx2 REAL
DECLARE @.ny2 REAL
DECLARE @.nz2 REAL
SET @.d2r = DBO.CARTESIAN_PI() / 180;
SET @.nx1 = DBO.CARTESIAN_COS(@.lat1 * @.d2r) * DBO.CARTESIAN_COS(@.lon1 * @.d2r);
SET @.ny1 = DBO.CARTESIAN_COS(@.lat1 * @.d2r) * SIN(@.lon1 * @.d2r);
SET @.nz1 = SIN(@.lat1 * @.d2r);
SET @.nx2 = DBO.CARTESIAN_COS(@.lat2 * @.d2r) * DBO.CARTESIAN_COS(@.lon2 * @.d2r);
SET @.ny2 = DBO.CARTESIAN_COS(@.lat2 * @.d2r) * SIN(@.lon2 * @.d2r);
SET @.nz2 = SIN(@.lat2 * @.d2r);
RETURN (60 * 2 * (1 / @.d2r) * ASIN(SQRT((@.nx1 - @.nx2) * (@.nx1 - @.nx2)
+ (@.ny1 - @.ny2) * (@.ny1 - @.ny2)
+ (@.nz1 - @.nz2) * (@.nz1 - @.nz2)
) / 2));
END
Cool!
Might want to double check the precisions. Real number precision confuses the hell out of me. I never feel 100% comfortable that I have allocated enough for the application.
Also. . . if you are doing alot of this, you might want to investigate MapInfo or ESRI for some really slick GIS db extensions.
Calculating Dates
the Finalsuit table is suppose to calculate the renewal dates(which I'm trying to do in a query) my original expression in access was using dateserial FirstRenewal: DateSerial(Year([FINALSUITDONE])+2,Month([FINALSUITDONE])+1,Day([FINALSUITDONE])=30), but sql does not recognize that.
For Example
If the Finalsuit is 12/01/2000
then the renewal would be 12/31/2002
the renewal are to be done on the last day of the month and two years from the finalsuit date. Problems is I'm having problems doing this in sql servers query?
Can someone out there help pleaseI think I've got the syntax right on this, but I just had a beer so can't be (hic) sure:
dateadd(day, -1, convert(char(10), dateadd(month, 25, [FINALSUITDONE]), 120)+'-01')
Adds 25 months to [FINALSUITDONE] to get the month FOLLOWING the month you want. Then CONVERTS to the first day of that month, and the subtracts 1 day to get that last day of the month 24 months (2 years) from the date you started with.|||thank you for replying, but it gave me an error message saying "your entry can not be converted to a valid datetime entry"
So frustrated
thank you for trying to help though I sure do appreciate it.
back to the books|||do this SELECT CAST(FINALSUITDONE AS DATETIME) FROM table. See if that gives you an error. If it does, you need to find out whatever entry is not a proper datetime and fix it before anything you do like this will work.|||No, do this:
1) Wait 2 hours after drinking a beer before posting any forum answers.
2) Post the correct syntax:
dateadd(day, -1, convert(char(7), dateadd(month, 25, [FINALSUITDONE]), 120)+'-01')
...should have use "convert(char(7)..." instead of "convert(char(10)..." :o|||hmmmmmmmm, IT'S BRIIIIIILIANT.|||Brilliant!|||Thank you so much Blindman for your help, I was really starting to get stressed out. By the way your very funny, I'll take your advice and have a couple of beers.
Wish I had your knowledge, still working towards it|||What a drunken genious
We have a lot of them here ... :D
Calculating Age based on Document Date in months
The variables would be:
{DOCUMENT.CLINICALDATE}
{PERSON.DATEOFBIRTH}The next will calculate age in years
({DOCUMENT.CLINICALDATE} - {PERSON.DATEOFBIRTH}) / 365
The next will calculate age in months
({DOCUMENT.CLINICALDATE} - {PERSON.DATEOFBIRTH}) / 365 * 12
Calculating a percentage using aggregate task
Hi,
I have a column called QTY and I need to calculate the percentage for each row based on the total sum of the column. They are all decimals. I have an OLE DB source that is reading the table used an aggregate task using the QTY column with operation SUM and called the output SUM OF QTY. Then I have a Derived Column task that takes the QTY column / SUM OF QTY * 100 to create the percentage. My numbers are not coming out correctly and when I put a data viewer from the aggregate task, it shows the same number for both columns:
QTY SUM OF QTY
0.01833 0.01833 (this should be the sum of all the decimals in the QTY col)
What am I doing wrong? ![]()
Thanks in advance!
Isabelle
You might have to use a multitask component to get this to work. The aggregate transformation does not pass fields through. So from the multitask output, you can take one path to the aggregate, and another to a sort. Take the output of the aggregate and put it in a sort as well. Then, take the two sorts and hook them up with a merge join on the common keys. Then, you'll have your original data, along with the aggregate column.|||Thanks for your response. I tried what you suggested and I still could not get it to work. Even when I created a sort column for both and then used a join merge, I still got the same amound in both columns. I ended up doing the conversion using Execute SQL task and saved the output as a variable and then just called the variable in a derived column and that worked.
Isabelle
Calculating a percentage using aggregate task
Hi,
I have a column called QTY and I need to calculate the percentage for each row based on the total sum of the column. They are all decimals. I have an OLE DB source that is reading the table used an aggregate task using the QTY column with operation SUM and called the output SUM OF QTY. Then I have a Derived Column task that takes the QTY column / SUM OF QTY * 100 to create the percentage. My numbers are not coming out correctly and when I put a data viewer from the aggregate task, it shows the same number for both columns:
QTY SUM OF QTY
0.01833 0.01833 (this should be the sum of all the decimals in the QTY col)
What am I doing wrong? ![]()
Thanks in advance!
Isabelle
You might have to use a multitask component to get this to work. The aggregate transformation does not pass fields through. So from the multitask output, you can take one path to the aggregate, and another to a sort. Take the output of the aggregate and put it in a sort as well. Then, take the two sorts and hook them up with a merge join on the common keys. Then, you'll have your original data, along with the aggregate column.|||Thanks for your response. I tried what you suggested and I still could not get it to work. Even when I created a sort column for both and then used a join merge, I still got the same amound in both columns. I ended up doing the conversion using Execute SQL task and saved the output as a variable and then just called the variable in a derived column and that worked.
Isabelle
Friday, February 10, 2012
calculated value based on values in other row
in a table i have 3 fields
custnr w
nr profitexample
1 1 100
1 2 110
1 3 120
1 4 150
i want to calculate how much the profit grows referenced from w
nr 1 andthe relative to the precedent w

1 1 0% 0%
1 2 10% 10%
1 3 20% 10%
1 4 50% 30%
thanksXavier wrote:
> i want to calculate how much the profit grows referenced from w
nr> 1 and the relative to the precedent w

> 1 1 0% 0%
> 1 2 10% 10%
> 1 3 20% 10%
> 1 4 50% 30%
This should work:
select profit/ (select top 1 TB2.profit from table TB2 where TB2.w
nr< TB1.w
nr order by w
nr DESC) from table TB1HTH,
Stijn Verrept.|||thanks for your help,
in the table there are a lot of custnr.
The corect form of the example table is analog to the custNr 1 there are
also Nr like
custnr w
nr profitexample
1 1 100
1 2 110
1 3 120
1 4 150
2 1 100
2 2 120
2 3 140
2 4 160
3 1 100
3 2 120
3 3 130
3 4 140
...
how can i extend to have a corect calculation for all customer
best regards
"Stijn Verrept" wrote:
> Xavier wrote:
>
>
> This should work:
> select profit/ (select top 1 TB2.profit from table TB2 where TB2.w
nr> < TB1.w
nr order by w
nr DESC) from table TB1> --
> HTH,
> Stijn Verrept.
>|||Xavier wrote:
> ...
> how can i extend to have a corect calculation for all customer
select profit/ (select top 1 TB2.profit from table TB2 where TB2.w
nr< TB1.w
nr and TB2.custnr= TB1.custnr order by w
nr DESC) from table TB1HTH,
Stijn Verrept.|||yes, it works, thanks
best regards
Xavier
calculated sum
Sum(measure) where dimension = "Top". Any ideas on how to accomplish this.No ideas? Seems to be a pretty basic function.|||Do you want the report user to interactively select a dimension value, and have the sum adjusted accordingly? In that case, you could set up a filter on the dataset, where the expression is the dimension column value, the operator is "=" and the value to compare against is the input parameter value.|||Nope. I just want to do a sum based on a dimension. Something like this.
Dataset1
Country Quantity
USA 1
USA 3
CANADA 1
MEXICO 3
CANADA 2
The sysntax I would use in Business Objects would be:
SUM(QUANTITY) WHERE(COUNTRY = "USA")
this expression would return 4.|||
Not sure if this solution will work for you, but you can add a Calculated Field to the Data Set, say: "FilteredQty", defined as (assuming Quantity is an integer):
CInt(iif(Fields!Country.Value = "USA", Fields!Quantity.Value, 0))
Then in your report you can use this expression:
Sum(Fields!FilteredQty.Value), wich should return 4 rather than 10
To make it dynamic, "USA" can be replaced by a report parameter.
|||Beautiful!! Works great. Thank you for your help.