Showing posts with label value. Show all posts
Showing posts with label value. Show all posts

Friday, March 30, 2012

How to value parameters for sqldatasource

I set up a sqldatasource based on a stored procedure which takes one parameter. The sqldatasrouce wizard generates the following code for the parameter below. The question is how do I value the DeptID parameter on the load of the form. I tried the following code in the load of the page, but get a null reference error:

Me.SqlDataSource1.InsertParameters("DeptID").DefaultValue = Session("DeptID")

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:FDConn %>"
SelectCommand="GetTruckStatus" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="DeptID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<radG:RadGrid ID="RadGrid1" runat="server">
</radG:RadGrid>

You've set the value of an InsertParameter, but you are performing a Select, not an Insert. Anyway, the SqlDataSource offers a number of different parameter types. One of them is an <asp:SessionParameter>. Use that instead of the generic<asp:Parameter> that you are currently using. You can reconfigure the SqlDataSource to generate it automatically. Click the WHERE button when applying the Select Statement, and in the Source dropdown, choose Session.

|||

Mike,
Thanks for the information. I went back into the configure the sqldatasrouce, but if you chose to use a stored procedure, the button for selecting "Where" is grayed out. I assumed that since the code was generated from vb and from the stored procedure I selected, vb would know the type of parameter it had to generate.


Regards,
Tom

|||

Mike,

I went back into the code and used the "SelectParameter" type and all worked well. Thanks for pointing me in the right direction.

Tom

Wednesday, March 28, 2012

How to validate the parameter values?

Hi,

Is there any way to validate the input paratemers for the report? For example: I want to restrict the value to be less than 100 in one parameter. How to achieve this?

Thnx in advance.

There is no way to validate and inform the user if the parameter value is not in a given range. Though you can restrict the values that user can select for the parameter by providing pre-defined available values to the parameter, either from query or non-queried.

Shyam

|||

Pre-defining the values will be helpful in case of numeric or string values. What if i want to compare date values. For example:

given date is less than or equal to today's date... I think, this is also not possible!!!

The RS Engine validates the date based on the format only. The validations are not possible.

Some alternative should be thought-of by microsoft... as validations are very necessary.

How to use variables as a Counter?

While inserting data into a target table, I'm trying to populate a primary key ID field sequentially. For each record, the value of the primary key field needs to be incremented by one (a counter).

I've tried to use the RowCount transformation to store the values in a variable. I'm able to successfully do that; however, I don't know how to read or update the variable incrementally.

If someone knows how to perform this task, please let me know. I would greatly appreciate it.

I think this: http://www.sqlis.com/default.aspx?37 should do what you need.


As will this: http://www.sqlis.com/default.aspx?93

They both do the same thing. One uses script, one is a custom component.

-Jamie

|||

I used the script component and it does exactly what I need it to do.

Thanks, Jamie.

Monday, March 26, 2012

how to use variable to create index

Hi ,

I would like to create index for a table and that index name must be random generated.

How to do this?

declare @.value varchar(50)

set @.value = rand()

set @.value = @.value + 'index-name'

create index @.value on tablename(variables)

Here it is:

IF OBJECT_ID('T1') IS NOT NULL
DROP TABLE T1;

CREATE TABLE T1(
id int primary key,
[Name] sysname,
code sysname
)
GO

declare @.value varchar(50);
set @.value = rand()
set @.value = @.value + 'index-name'

declare @.cmd sysname;
SET @.cmd = 'CREATE INDEX [' + @.value + '] ON T1([Name])';

EXEC(@.cmd);

Thanks,
Zuomin

How to use value of a variable in defining data type

HI Experts,

I have same table structures in two database and one master table which contains Table id, Table name,primary key, data type of primary key. i have to comapare
Tables in both tha database and as per result i have to do insert,update or delete.

for that i have written query :

DECLARE @.rowcount_mastertable FLOAT
SET @.rowcount_mastertable = (select count(*) from master_table)

DECLARE @.TABLE_ID float,
@.TABLE_NAME varchar (100),
@.primary_key varchar (100),
@.Primarykey_DATATYPE varchar (50),

DECLARE @.COUNTER FLOAT
SET @.COUNTER = 1

WHILE (@.Counter <= @.rowcount_mastertable)

Begin

SET @.TABLE_NAME = (SELECT TABLE_NAME FROM MASTER_TABLE TABLE_ID = @.COUNTER)
SET @.primary_key = (SELECT primary_key FROM MASTER_TABLE WHERE TABLE_ID = @.COUNTER)
SET @.Primarykey_DATATYPE = (SELECT Primarykey_DATATYPE FROM MASTER_TABL WHERE TABLE_ID = @.COUNTER)

--In below line i want to declare a variable and datatype should be same as what we got from master table so that i can use this @.MAX_primary_key to fetch max of primary key from table name where table id is 1

DECLARE @.MAX_primary_key @.Primarykey_DATATYPE
SELECT @.MAX_primary_key = MAX(@.primary_key) FROM @.TABLE_NAME
WHERE TABLE_ID = @.COUNTER

--But by running it i am getting error that "Incorrect syntax near '@.Primarykey_DATATYPE'. and "Must declare the variable '@.MAX_primary_key'.

Please suggest

Thanks in Advance

Quote:

Originally Posted by aviansh

HI Experts,

I have same table structures in two database and one master table which contains Table id, Table name,primary key, data type of primary key. i have to comapare
Tables in both tha database and as per result i have to do insert,update or delete.

for that i have written query :


DECLARE @.rowcount_mastertable FLOAT
SET @.rowcount_mastertable = (select count(*) from master_table)

DECLARE @.TABLE_ID float,
@.TABLE_NAME varchar (100),
@.primary_key varchar (100),
@.Primarykey_DATATYPE varchar (50),

DECLARE @.COUNTER FLOAT
SET @.COUNTER = 1

WHILE (@.Counter <= @.rowcount_mastertable)

Begin

SET @.TABLE_NAME = (SELECT TABLE_NAME FROM MASTER_TABLE TABLE_ID = @.COUNTER)
SET @.primary_key = (SELECT primary_key FROM MASTER_TABLE WHERE TABLE_ID = @.COUNTER)
SET @.Primarykey_DATATYPE = (SELECT Primarykey_DATATYPE FROM MASTER_TABL WHERE TABLE_ID = @.COUNTER)

--In below line i want to declare a variable and datatype should be same as what we got from master table so that i can use this @.MAX_primary_key to fetch max of primary key from table name where table id is 1

DECLARE @.MAX_primary_key @.Primarykey_DATATYPE
SELECT @.MAX_primary_key = MAX(@.primary_key) FROM @.TABLE_NAME
WHERE TABLE_ID = @.COUNTER


--But by running it i am getting error that "Incorrect syntax near '@.Primarykey_DATATYPE'. and "Must declare the variable '@.MAX_primary_key'.


Please suggest

Thanks in Advance



Examine this line more closely...

DECLARE @.MAX_primary_key @.Primarykey_DATATYPE

at what point are you declaring either of these variable datatypes?

Jim :)

How to use two aggregate functions in RS 2005

I am not able to use two aggregate functions to display a value in a
table.
Basically it is (Sum of (Sum of X)).
How do we get around this?
Please let me know.
ThanksWhat might work for you is to add a calculated field. On the field list
where you drag and drop from just do a right mouse click, add a field (or
something like that). Then you can do a sum of that.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Anup" <anupkm@.gmail.com> wrote in message
news:1165428357.174972.171260@.l12g2000cwl.googlegroups.com...
>I am not able to use two aggregate functions to display a value in a
> table.
> Basically it is (Sum of (Sum of X)).
> How do we get around this?
> Please let me know.
> Thanks
>|||Hi Bruce,
Thank you very much for your reply.
So you mean to say that I need to add that field as a calculated field
instead of a normal field?
Thanks
Anup
Bruce L-C [MVP] wrote:
> What might work for you is to add a calculated field. On the field list
> where you drag and drop from just do a right mouse click, add a field (or
> something like that). Then you can do a sum of that.
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "Anup" <anupkm@.gmail.com> wrote in message
> news:1165428357.174972.171260@.l12g2000cwl.googlegroups.com...
> >I am not able to use two aggregate functions to display a value in a
> > table.
> > Basically it is (Sum of (Sum of X)).
> >
> > How do we get around this?
> > Please let me know.
> >
> > Thanks
> >|||If you add a calculated field to your dataset (this is from the list of
field, I am not talking about a sql statement here) you can have the
calculated field be an aggregate. Then you can aggregate the calculated
field, getting around your problem. I do this to make things simplier too.
Try it as I mentioned and see if it makes sense in your situation. Adding a
field manually to the field list returned by the query is not very
discoverable.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Anup" <anupkm@.gmail.com> wrote in message
news:1165432174.432662.162930@.f1g2000cwa.googlegroups.com...
> Hi Bruce,
> Thank you very much for your reply.
> So you mean to say that I need to add that field as a calculated field
> instead of a normal field?
> Thanks
> Anup
> Bruce L-C [MVP] wrote:
>> What might work for you is to add a calculated field. On the field list
>> where you drag and drop from just do a right mouse click, add a field (or
>> something like that). Then you can do a sum of that.
>>
>> --
>> Bruce Loehle-Conger
>> MVP SQL Server Reporting Services
>> "Anup" <anupkm@.gmail.com> wrote in message
>> news:1165428357.174972.171260@.l12g2000cwl.googlegroups.com...
>> >I am not able to use two aggregate functions to display a value in a
>> > table.
>> > Basically it is (Sum of (Sum of X)).
>> >
>> > How do we get around this?
>> > Please let me know.
>> >
>> > Thanks
>> >
>|||Thanks Bruce. Here is my situation:
I need to display the "Double Sum" Value in the footer of a table.The
details of this table is in a different level of grouping and footer is
at a different level of grouping.
Thanks
Anup
Bruce L-C [MVP] wrote:
> If you add a calculated field to your dataset (this is from the list of
> field, I am not talking about a sql statement here) you can have the
> calculated field be an aggregate. Then you can aggregate the calculated
> field, getting around your problem. I do this to make things simplier too.
> Try it as I mentioned and see if it makes sense in your situation. Adding a
> field manually to the field list returned by the query is not very
> discoverable.
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "Anup" <anupkm@.gmail.com> wrote in message
> news:1165432174.432662.162930@.f1g2000cwa.googlegroups.com...
> > Hi Bruce,
> >
> > Thank you very much for your reply.
> >
> > So you mean to say that I need to add that field as a calculated field
> > instead of a normal field?
> >
> > Thanks
> > Anup
> >
> > Bruce L-C [MVP] wrote:
> >> What might work for you is to add a calculated field. On the field list
> >> where you drag and drop from just do a right mouse click, add a field (or
> >> something like that). Then you can do a sum of that.
> >>
> >>
> >> --
> >> Bruce Loehle-Conger
> >> MVP SQL Server Reporting Services
> >>
> >> "Anup" <anupkm@.gmail.com> wrote in message
> >> news:1165428357.174972.171260@.l12g2000cwl.googlegroups.com...
> >> >I am not able to use two aggregate functions to display a value in a
> >> > table.
> >> > Basically it is (Sum of (Sum of X)).
> >> >
> >> > How do we get around this?
> >> > Please let me know.
> >> >
> >> > Thanks
> >> >
> >

Friday, March 23, 2012

How to Use Suppressed Formula?

Hi!
i am devleoping a application using with visual basic and crystal reports 8.5. i would like to know

how to suppress the field value when the both entries are same?

like : table.filedname="January"
plz explain.Right click on the field
Select Format section
Goto Suppress option
There is button labelled x-2
Click that and write this

table.filedname="January"

how to use stored proc output?

I want to check that the srv_datasource value of a liked server is still
pointing at the correct location.
I can run the stored proc
sp_linkedservers
and see that the value is correct...but how can I do that programmatically?
I mean how do I actually code to look at the value of srv_datasource for a
given value of srv_name returned by the sp_linkedservers stored proc?
Al Blake, Canberra, AustraliaThe datasource & provider string are retrieved from master..sysservers
table. You can either query it directly like:
SELECT *
FROM master.dbo.sysservers
WHERE srvname = @.server ;
or you can get the resultset of sp_linkedservers into a #temp table & query
from the table.
Anithsql

Wednesday, March 21, 2012

How to use SCOPE_IDENTITY() in 4-layer architecture

I have the following stored procedure:

INSERT INTO MyTable( Value1, Value 2)

VALUES( @.Value1, @.Value2)

SELECT SCOPE_IDENTITY()

How do I put this sp in the DAL typed dataset, so I can get the Identity value in the Business Layer?

From the DAL execute a query and use cmd.ExecuteScalar() this will return the identity field...

Please specify more details if this won't help you

|||

Hi,

You can use a SqlDataAdapter to execute this stored procedure as a common SELECT query. The result set will be filled into a DataSet. And the first row, first column of the first table will be the scope identity.

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!

Monday, March 19, 2012

How To Use Return Value from SqlDataSource

I have the following code in my page:

<asp:SqlDataSourceID="SqlHolidayDateRange"runat="server"ConnectionString="(OurConnectionString)"

SelectCommand="CountHolidays"SelectCommandType="StoredProcedure">

<SelectParameters><asp:ControlParameterControlID="WeekEndingDatePicker"Name="EndDate"PropertyName="SelectedDate"/><asp:ParameterDirection="ReturnValue"Name="RowCount"Type="Int32"/></SelectParameters></asp:SqlDataSource>

I need to place RowCount, the returned integer value from the stored procedure CountHolidays into a field on the web page. How in the world do I access that data?

Everything I've been able to find works if I'm defining my own command object and writing this thing from scratch. What I - and you -have to work with is what's above.

Hi,

Add OnSelected="SqlHolidayDateRange_Selected" to SqlDataSource then you can get return value using

Convert.ToInt32(e.Command.Parameters["@.RowCount"].Value);

Hope this helps.

|||

Like this:

voidSqlHolidayDateRange_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
int RowCount = Convert.ToInt32(e.Command.Parameters["@.RowCount"].Value);

//add your code.......

}

|||I'm sorry, but I'mreally new at this. Neither of your answers make much sense to me. Where do I add those things? In the page, in the codebehind, or what?|||

Doesn't matter.

Add OnSelected="SqlHolidayDateRange_Selected" in your page:

<asp:SqlDataSourceID="SqlHolidayDateRange"runat="server"ConnectionString="(OurConnectionString)"

SelectCommand="CountHolidays"SelectCommandType="StoredProcedure">

OnSelected="SqlHolidayDateRange_Selected"

<SelectParameters>

<asp:ControlParameterControlID="WeekEndingDatePicker"Name="EndDate"PropertyName="SelectedDate"/>

<asp:ParameterDirection="ReturnValue"Name="RowCount"Type="Int32"/>

</SelectParameters>

</asp:SqlDataSource>

And add the following to you code-behinde:

void SqlHolidayDateRange_Selected(object sender, SqlDataSourceStatusEventArgs e) {int RowCount = Convert.ToInt32(e.Command.Parameters["@.RowCount"].Value);//add your code.......}

Then you can display RowCount .

You can take a look atSqlDataSource in QuickStart Tutorials.

how to use parameter value as a column name

I am feeding in @.RsCategory varchar (25) into my stored procedure. I was hoping to make the RsCategory = the column name from the table I would like to select data from.

How can I use @.RscCategory as the column name value in the select statement? (or can I?)

select @.RsCategory as displaydata

From tTable T

where T.MyOtherParams=@.MyOtherParams

Any help would be greatly appreciated!

One way is to use dynamic SQL

DELCARE @.strSQL = 'SELECT ' + @.RsCategory + 'AS displaydata FROM tTable T WHERE MyOtherParam=' + @.MyOtherParams

EXEC @.strSQL

|||

You got the answer to your question. But what are you trying to do actually by sending the column name to be selected from client side? You can either write different SELECT statements in your SP or return the minimal data that you need and let the client hide the columns based on the configuration. Using dynamic SQL is simple but it has lot of security and maintainence issues. For example, the posted code doesn't protect against SQL injection attacks. You can do that by using QUOTENAME on the passed column name parameter.

An alternative approach is to use CASE expression as shown below which will work if the columns are compatible data types:

select case @.RscCategory

when 'Col1' then t.Col1

when 'Col2' then t.Col2

end as displaydata

Friday, March 9, 2012

how to use if...else

i have 4 columns that hold phone numbers. at least one has to be filled in.
how could i select the first one with a value in it
i tried:
SELECT (IF PhoneWork != '' BEGIN (SELECT CAST(PhoneWork AS bigint)) END ELSE
(SELECT CAST('0' AS bigint))) AS PhoneWork FROM Customers
but that isnt working. its not checking the other 3 columns: PhoneHome,
PhoneFax, PhoneOther, because i got an error: Incorrect syntax near ')'
thanks for your help.have u tried CASE
SELECT
CASE
WHEN PhoneWork1 IS NOT NULL THEN PhoneWork1
WHEN PhoneWork2 IS NOT NULL THEN PhoneWork2
WHEN PhoneWork3 IS NOT NULL THEN PhoneWork3
WHEN PhoneWork4 IS NOT NULL THEN PhoneWork4
END
FROM Customers|||Abraham Luna,
See function COALESCE in BOL.
Example:
select coalesce(c1, c2, c3, c4) as c
from
(
select 1, cast(null as int), cast(null as int), cast(null as int)
union all
select cast(null as int), 2, cast(null as int), cast(null as int)
union all
select cast(null as int), cast(null as int), 3, cast(null as int)
union all
select cast(null as int), cast(null as int), cast(null as int), 4
) as t1(c1, c2, c3, c4)
go
AMB
"Abraham Luna" wrote:

> i have 4 columns that hold phone numbers. at least one has to be filled in
.
> how could i select the first one with a value in it
> i tried:
> SELECT (IF PhoneWork != '' BEGIN (SELECT CAST(PhoneWork AS bigint)) END EL
SE
> (SELECT CAST('0' AS bigint))) AS PhoneWork FROM Customers
> but that isnt working. its not checking the other 3 columns: PhoneHome,
> PhoneFax, PhoneOther, because i got an error: Incorrect syntax near ')'
> thanks for your help.
>
>|||>i have 4 columns that hold phone numbers. at least one has to be filled in.
>how could i select the first one with a value in it
CREATE TABLE dbo.foo
(
PhoneWork VARCHAR(32),
PhoneHome VARCHAR(32),
PhoneFax VARCHAR(32),
PhoneOther VARCHAR(32)
)
GO
SET NOCOUNT ON
INSERT dbo.foo SELECT '555',NULL,NULL,NULL
INSERT dbo.foo SELECT '555',NULL,'222',NULL
INSERT dbo.foo SELECT NULL,'333',NULL,NULL
INSERT dbo.foo SELECT NULL,NULL,NULL,'444'
INSERT dbo.foo SELECT NULL,NULL,'666',NULL
INSERT dbo.foo SELECT NULL,NULL,NULL,NULL
INSERT dbo.foo SELECT NULL,NULL,NULL,'x'
GO
SELECT PhoneWork = COALESCE
(
NULLIF(PhoneWork, ''),
NULLIF(PhoneHome, ''),
NULLIF(PhoneFax, ''),
NULLIF(PhoneOther,''),
'0'
)
FROM dbo.foo
GO
DROP TABLE dbo.foo
Why are you casting this as a BIGINT? How are you preventing non-numeric
values from being entered into any of these columns? What on earth is a
PhoneFax?|||thank you for your answer
"Manshu" <upadhyay.himanshu@.gmail.com> wrote in message
news:1126012613.765505.60260@.g49g2000cwa.googlegroups.com...
> have u tried CASE
> SELECT
> CASE
> WHEN PhoneWork1 IS NOT NULL THEN PhoneWork1
> WHEN PhoneWork2 IS NOT NULL THEN PhoneWork2
> WHEN PhoneWork3 IS NOT NULL THEN PhoneWork3
> WHEN PhoneWork4 IS NOT NULL THEN PhoneWork4
> END
> FROM Customers
>|||LOL,
thank you for your answer. i cast it as a bigint because the gridview
boundfield dataformatstring is set to {0:(###) ###-####} and it only works
on integer columns. i can't figure out how to format strings using the
dataformatstring property (if you know how let me know).
phonefax is there fax number :)
they tried to keep the naming convention of PhoneXXX where XXX is the type
of phone number.
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:%23SR4WXusFHA.260@.TK2MSFTNGP11.phx.gbl...
>
> CREATE TABLE dbo.foo
> (
> PhoneWork VARCHAR(32),
> PhoneHome VARCHAR(32),
> PhoneFax VARCHAR(32),
> PhoneOther VARCHAR(32)
> )
> GO
> SET NOCOUNT ON
> INSERT dbo.foo SELECT '555',NULL,NULL,NULL
> INSERT dbo.foo SELECT '555',NULL,'222',NULL
> INSERT dbo.foo SELECT NULL,'333',NULL,NULL
> INSERT dbo.foo SELECT NULL,NULL,NULL,'444'
> INSERT dbo.foo SELECT NULL,NULL,'666',NULL
> INSERT dbo.foo SELECT NULL,NULL,NULL,NULL
> INSERT dbo.foo SELECT NULL,NULL,NULL,'x'
> GO
> SELECT PhoneWork = COALESCE
> (
> NULLIF(PhoneWork, ''),
> NULLIF(PhoneHome, ''),
> NULLIF(PhoneFax, ''),
> NULLIF(PhoneOther,''),
> '0'
> )
> FROM dbo.foo
> GO
> DROP TABLE dbo.foo
>
> Why are you casting this as a BIGINT? How are you preventing non-numeric
> values from being entered into any of these columns? What on earth is a
> PhoneFax?
>

How to use floor to ....

I am in a SQL class and the teacher has asked us to update a value by 100 if the id number is even using the floor function.

I am not looking for someone to write the expresion, but someone to explain how the floor function could be used to do this.

Any help would be greatly appreciated.your lecturere probably wants to to divide your number by 2, get the floor() value and multiply it by 2 again to see if it is the same value

eg
7/2 = 3.5
floor(3.5) = 3
3 x 2 = 6

so we know 7 is not even

8/2 = 4
floor(4) = 4
4 x 2 = 8

so we know 8 is even|||Thanks a ton.

That was just the info i need to build my query. My brain must have been mush to not figure out that simple math.

just for FYI here is the query i cam up with, nothing complicated but with your help on the math i was able to come through.

UPDATE Salaries
SET Salary = Salary + 100
WHERE floor(empid / 2) * 2 = empid

UPDATE Salaries
SET Salary = Salary + 200
WHERE floor(empid / 2) * 2 != empid

Thanks again Matt, your a lifesaver!!!!

How to use fields value in code functions

Hello,
I wrote a function in vb.net and i Sent her parameter.
The function is used in a table cell.
I want the function to use a field value,
I tried :
Fileds!myFilesName.Value

But it didn't work.
Can I do this kind of thing?

Thanks.

Are you trying to write or read from a table cell? Or is it from a control in the table cell?

|||

Hi TaTworth.

I'm trying to read the value from the current row in the dataset and write it to the table cell.

I'll will try to explain again:
I have a table in my report.
in one of the cells I have a filed. something like:

=Fields!FieldName.Value

Now, Let say I want to add him the value "2". I will use:

=Fields!FieldName.Value + 2

Now, let say that I want to call a function that will add him the
value "2" and return the result.

I can use the following call:

=Code.AddTwoFunction(Fields!FieldName.Value)

And in my code I will get the Filed value as parameter and add him the
2.

What I wanted to know is if I can call the function with out the
parameter and tell her to automaticlly get the value of the field from
the row she was called?

The reason I need this is that I have a function that need to get 5
fileds and when I call it it looks some thing like:

=Code.AddTwoFunction(Fields!FieldName.Value,Fields!
FieldName2.Value,Fields!FieldName3.Value,Fields!
FieldName4.Value,Fields!FieldName5.Value)

What I would like to do is to call the function from the cell like =Code.AddTwoFunc()

and inside the function use something like:

dim str = Fields!FieldName.Value + 2;

The problem is that it doesn't recognize the"Fields!FieldName.Value"

Hope I explain my self better

|||

Shalom Shabbat AspNetO

You can go two ways - one way is to modify the dataset prior to binding to a datagrid, the other is to set up a suitable table structure to contain all your data cells, giving each cell its own runat="server" and its own id value, you can then read and write from each cell. When reading use a NullToString functions as in http://forums.asp.net/p/1091080/1635818.aspx#1635818 and then cast the string to an integer.

Thus if the contents of tddA1, tddA2 are to be added to give tddA3, then

string sA1 = NullToString(tddA1.InnnerText);
string sA2 = NullToString(tddA2.InnnerText);
int iA1 = System.Convert.ToInt32(sA1);
int iA2 = System.Convert.ToInt32(sA2);
tddA3.InnerText = (iA1 + iA2).ToString();

How to use Fields or ReportItems value in charts

Hi, all. I am doing a financial report needs to show last 10 yrs history data. The end year is the last year of the current year. How can I set the minumum and maximun with Year(Now) fucntion for the x-axis, to represent the years? Is there any way to use Fields value for the chart minumum and maximun?

Yes this is possible in RS 2005 (but not in RS 2000). Axis settings such as min/max/crossat/major interval/minor interval can be expression-based. Just type in the expression as e.g. =Year(Now)

-- Robert

|||Thanks Robert. Actually I want to put the Year(Now)(2006) as maximun and Year(Now) -10(1996) as Minimun. However, the data I have are bewteen 1998 and 2002, so the chart still shows data from 1998 to 2002. Can I set exactly 10 years on the chart? Even thought there're no data at 2006 and 1996?|||

This should work fine if the x-axis is set to use "numeric / time-scale values" and the category grouping expression evaluates to either integer values or DateTime objects.

-- Robert

how to use equal sign (=) as an available value for a parameter?

Is there a way to use the equal sign (=) as an available value for a parameter?
It's working with the rest of the comparison operators: <>, >, >=, <, <=.

Thank you!

I'm not sure what the equal sign is going to be used as, but yes you shouldn't have a problem setting it as an available value if you make the data type a string.

Then just use this as the expression for the non-queried value: ="="

|||

Assuming the parameter is defined as a string try ="=".

One problem I have found with this type of parameter is that if it is not defined as the first parameter is it will be 'greyed out' and you will get a 'hiccup" as it tries to evalutate the formula.

|||

I want the users to be able to choose one of the comparison operators to filter a numeric field. Something like: Balance = 0 or Balance > 500.
So one of the parameters it's going to collect the comparison operator and another parameter will collect the numeric value and feed the stored procedure.

In the available values that are defining the Operator parameter I have this:
Label Value
not equal <>
greater than >
greater or equal than >=
less than <
less or equal than <=
The parameter is defined as string.

For the rest of comparison operators I don't have for example =">" but > and the report is returning the correct results.
Trying to have just = for the value column will give an error which is normal since = is used to build an expression.
But trying your solution to use ="=" it's not working.
I guess I'm missing something and I don't know exactly what.

Thank you for your reply

|||

I'm still unsure as to how you are creating a query with these parameters. However, one thing you can try is to use an if statement and check for "=". Then, if it matches perform the equal query, otherwise use the actual parameter value.

|||

It worked with ="=". My mistake...
I've changed the way the stored procedure was built.
Initially I was transfering to the stored procedure the operator and the numeric value concatenated already.
The change I've made is to use separate input parameters for the stored procedure instead of transfering them concatenated.
In this way it's working to use ="=".

I've also experienced what Lonnie remarked.
The parameter that is using ="=" needs to be the first parameter otherwise it will be disabled.
It's kind of annoying if you don't want this parameter to appear as the first one.

Thank you guys...

Wednesday, March 7, 2012

How to use date function in sql server

Hi

I am trying to do a simple select using a date value.

For eg:-
in oracle i would do the following
select count(*) from TEMP_TABLE where to_char(modif_time,'mm/dd/yyyy')='10/04/03'

How do I accomplish the same in sqlserver?

Thanks in Advance
skYou can use the CONVERT function to transform a DATETIME column to a string
in a particular date format. In a WHERE clause though it makes more sense
not to convert the dates - otherwise the conversion will force a table scan
and the conversion will have to be performed for every row.

Instead, specify the range of DATETIME values you require:

SELECT COUNT(*)
FROM temp_table
WHERE modif_time>='20031004' AND modif_time<'20031005'

You can use any of the following styles of formatted string to specify dates
in code:

'20031231'
'2003-12-31T17:59:00'
'2003-12-31T17:59:00.000'

These are the "safe" ISO formats which are guaranteed to work independently
of any regional settings. Other formats such as mm/dd/yyyy are best avoided
because they are dependent on the server's regional settings and are
therefore less portable.

--
David Portas
----
Please reply only to the newsgroup
--|||David,

Tried your suggestion, works great. Thanks a lot.
I also tried using convert function to get counts for
multiple dates and works fine.
But I was trying to sort the rows using date, that
doesn't seem to work.

my query looks like this:-
select convert(varchar,modif_time,101),count(*) from TEMP_TABLE group by
convert(varchar,modif_time,101) order by convert(varchar,modif_time,101)

when I run it, the output looks like :-
01/01/2001
01/01/2002
01/01/2003
01/02/2001
01/02/2002
01/02/2003
01/03/2000
01/03/2001
01/03/2002
01/03/2003

As you can see, the sort order seems to be first 2 chars, then the next
2 chars and so on. I want it to be
01/03/2000
01/01/2001
01/02/2001
01/03/2001
01/01/2002
01/02/2002
01/03/2002
01/01/2003
01/02/2003
01/03/2003

this is the right date format. Is this possible? Any help
will be appreciated.

Thanks

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||sai (anonymous@.devdex.com) writes:
> Tried your suggestion, works great. Thanks a lot.
> I also tried using convert function to get counts for
> multiple dates and works fine.
> But I was trying to sort the rows using date, that
> doesn't seem to work.
> my query looks like this:-
> select convert(varchar,modif_time,101),count(*) from TEMP_TABLE group by
> convert(varchar,modif_time,101) order by convert(varchar,modif_time,101)
> when I run it, the output looks like :-
> 01/01/2001
> 01/01/2002
> 01/01/2003
> 01/02/2001
> 01/02/2002
> 01/02/2003
> 01/03/2000
> 01/03/2001
> 01/03/2002
> 01/03/2003
> As you can see, the sort order seems to be first 2 chars, then the next
> 2 chars and so on. I want it to be

Of course. You asked to sort on a character string, then SQL Server
will sort on a character string.

If you want to sort by date, there are two options:

1) Use a better date format, and still sort by string. Change 101 to
112 that is YYYYMMDD.

2) Use this somewhat convuluted query:

select convert(varchar, convert(datetime, dt), 101), cnt
from (select dt = convert(varchar, loadtime, 112), cnt = count(*)
from abasysobjects
group by convert(varchar, loadtime, 112)) as x
order by dt

(Column and table names changed to the table I used for the test.)

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Because your CONVERT function returns a string you need to make sure the
string is in the correct format for sorting. (YYYY-MM-DD):

SELECT CONVERT(CHAR(10),modif_time,120) AS modif_date,
COUNT(*)
FROM TEMP_TABLE
GROUP BY CONVERT(CHAR(10),modif_time,120)
ORDER BY modif_date

You might prefer to output a date rather than a string - leave the
formatting of the date to your client application:

SELECT CAST(CONVERT(CHAR(8),modif_time,112) AS DATETIME) AS modif_date,
COUNT(*)
FROM TEMP_TABLE
GROUP BY CAST(CONVERT(CHAR(8),modif_time,112) AS DATETIME)
ORDER BY modif_date

--
David Portas
----
Please reply only to the newsgroup
--

How to use criteria with text file source in DTS package?

I have a peculiar problem with a database.

I need to import data from text files where one column matches a value in a table that's already on the database. I cannot even fathom how to do this without pulling the entire 1GB file onto the database and simply deleting data that doesn't match the criteria. While this would work, I'm sure there's a more efficient way to do it! Can anyone give me some pointers? I'm not exactly a DTS expert.

Thank you.for this you will have to edit the column transformation ActiveX script generated by DTS. just need to add a "if" condition to skip the row in case the condition is not matching. something like below will do the job

Function Main()
if DTSSource("Src_Col_Name") = "Filter_Value" then
DTSDestination("Col1") = DTSSource("Col1")
DTSDestination("Col2") = DTSSource("Col2")
DTSDestination ............
Main = DTSTransformStat_OK
else
Main = DTSTransformStat_SkipRow
end if
End Function|||Is there an easier way to do this? The values I'm filtering by are held in a SQL table. I don't want to have to manually update these in the script because there will be several dozen policy IDs we're filtering by, and the table we're updating has 229 columns so that's a ton of scripting to do!

For example, we have a 1gb file we could import, but the people who use the DB are interested only in data pertaining to 30 policy IDs. They want us to import ONLY the data for those policy IDs; they don't want to see anything else.|||In your DTS function, write a few lines of VBA code to connect to the database and see if the current source row's policy ID exists in the table that holds the list of interesting policies.

-PatP|||Thanks for the suggestions, guys. :beer:

The way we ended up doing this is a very roundabout and slow. We're doing it in batches of 100,000 and putting the data into an intermediate table, running an update to put the data that matches the criteria into the final table, truncating the intermediate table, and going around to the start and doing it again until we get to the end of the file. This way, we managed to read through a 1GB text file and pull out only what we were interested in in our 200MB database. I know this is hideously inefficient and our DBAs would probably kill us if they knew about it but I did ask them for help and all they could do was point me in the direction of a couple of other programmers in the company who didn't have any ideas.

I'm not sure if we will continue to use this solution but it is so far the easiest one to maintain that we've thought of. I won't be at this job much longer (few months at the most) and when I leave the other team members (who are less experienced with SQL Server than I am, as horrifying as that thought is) have to maintain what I've written, so gigantic long ActiveX scripts are something I'd prefer to avoid if at all possible; some team members cannot write VBScript at all. Also, the words 'best practice' are unfortunately rarely uttered here. :mad:

Realistically we can't avoid ActiveX scripts; we have a few here and there, always to convert dates from one format to another, but the scripts suggested would just be too large for our team to handle. ActiveX definitely has its place though; I just wrote a script last week to convert Julian dates to Gregorian. No other way to do it than with a script! These suggestions may come in handy for a smaller-scale import too, so I'll tuck away a copy of the tread J.I.C. :D

How to use comma separated value list in the where clause?

How to use comma separated value list in the where clause?

I would like to do something like the following (Set voted = true for all rows in tblVoters where EmpID is in the comma separated value list).

update tbl_Voters

set voted = true

whereEmpID in @.empIdsCsv

Where, @.empIdsCsv = ’12,23,345,’ (IDs of the employees)

Since the above is not possible I have done the following dynamic query:

-- Convert the comma separated values to conditional statement like EmpID = {id} or EmpliD = {id}…

set @.empIdsCsv = 'EmpID=' + substring(@.empIdsCsv , 0, len(@.empIdsCsv ))-- Remove trailing comma

set @.empIdsCsv = replace(@.empIdsCsv , ',', ' or EmpID=')

declare @.markVoters varchar(8000)

set @.markVoters = '

update tbl_Voters

setvoted = true

where ’ + @.empIdsCsv

--Execute the dinamic query

exec (@.markVoters)

The above code generates the following dynamic query:

update tbl_Voters

setvoted = true

where

EmpID= 12 or EmpID=23 or EmpID=345

The obvious drawback here is the performance and the limitation of the dynamic query length (8000 chars).

Can someone suggest a better solution with the ability to use comma seperated values in the where clause?

there is the IN clause however I somehow get the feeling that will not help performance that much. The syntax is
select columns from tablename where EMplID IN (12, 23, 356, ....)

Hope this helps
|||

Please take a look at the link below that describes various techniques on how to pass a list of values from client to SQL Server.

http://www.sommarskog.se/arrays-in-sql.html

Friday, February 24, 2012

How to use BETWEEN with custom-ordered values

We have a 10 digit primary key value in this format: M000123456. The
order for this key is first determined by positions 3 and 4 in this
example, then positions 1 and 2. So a brief sample of correct ordering
would look like this:
M000001501
M000011501
M000021501
M000001601
M000011601
M000021601

Now my question: how can I use a BETWEEN (or > and <) in my WHERE
clause to get a range of values for this column? I use the following
ORDER BY clause to control how the results are sorted, but I can't get
the same logic to work with BETWEEN in a WHERE clause.

ORDER BY SUBSTRING(<fieldname>, 7, 2), SUBSTRING (<fieldname>, 5, 2)
How do I return values between M000011501 and M000011601 for example?On 19 Dec 2004 16:36:14 -0800, ian.proffer@.gmail.com wrote:

>We have a 10 digit primary key value in this format: M000123456. The
>order for this key is first determined by positions 3 and 4 in this
>example, then positions 1 and 2. So a brief sample of correct ordering
>would look like this:
>M000001501
>M000011501
>M000021501
>M000001601
>M000011601
>M000021601
>Now my question: how can I use a BETWEEN (or > and <) in my WHERE
>clause to get a range of values for this column? I use the following
>ORDER BY clause to control how the results are sorted, but I can't get
>the same logic to work with BETWEEN in a WHERE clause.
>ORDER BY SUBSTRING(<fieldname>, 7, 2), SUBSTRING (<fieldname>, 5, 2)
>How do I return values between M000011501 and M000011601 for example?

Hi Ian,

Usually, this kind of requirement is a sign of a bad table design. I have
the suspicion that both the two digits in position 3 and 4 and the two
digits in position 1 and 2 have a specific meaning in your business. If
that is the case, you should probably store these as seperate columns. You
can always paste the different values together for outputting as one
column.

Anyway, based on your ORDER BY clause, the BETWEEN predicate would read

WHERE SUBSTRING(<columnname>, 7, 2) + SUBSTRING (<columnname>, 5, 2)
BETWEEN SUBSTRING('M000011501', 7, 2) + SUBSTRING ('M000011501', 5, 2)
AND SUBSTRING('M000011601', 7, 2) + SUBSTRING ('M000011601', 5, 2)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi

It may be easier if you stored the correctly ordered string rather than the
one used for display, and have the display string in a view/computed column
or part of the select statement.

You don't say how the rest of the string is arranged, but something like:

SELECT SUBSTRING(<fieldname>, 7, 2) + SUBSTRING (<fieldname>, 5, 2) +
SUBSTRING (<fieldname>, 1, 4) + SUBSTRING (<fieldname>, 9, 2),
* FROM <tablename>
WHERE SUBSTRING(<fieldname>, 7, 2) + SUBSTRING (<fieldname>, 5, 2) +
SUBSTRING (<fieldname>, 1, 4) + SUBSTRING (<fieldname>, 9, 2) between
SUBSTRING('M000011501', 7, 2) + SUBSTRING ('M000011501', 5, 2) + SUBSTRING
('M000011501', 1, 4) + SUBSTRING ('M000011501', 9, 2)
and SUBSTRING('M000011601', 7, 2) + SUBSTRING ('M000011601', 5, 2) +
SUBSTRING ('M000011601', 1, 4) + SUBSTRING ('M000011601', 9, 2)
ORDER BY SUBSTRING(<fieldname>, 7, 2), SUBSTRING (<fieldname>, 5, 2)

will give your result.

John

<ian.proffer@.gmail.com> wrote in message
news:1103502974.453433.144600@.f14g2000cwb.googlegr oups.com...
> We have a 10 digit primary key value in this format: M000123456. The
> order for this key is first determined by positions 3 and 4 in this
> example, then positions 1 and 2. So a brief sample of correct ordering
> would look like this:
> M000001501
> M000011501
> M000021501
> M000001601
> M000011601
> M000021601
> Now my question: how can I use a BETWEEN (or > and <) in my WHERE
> clause to get a range of values for this column? I use the following
> ORDER BY clause to control how the results are sorted, but I can't get
> the same logic to work with BETWEEN in a WHERE clause.
> ORDER BY SUBSTRING(<fieldname>, 7, 2), SUBSTRING (<fieldname>, 5, 2)
> How do I return values between M000011501 and M000011601 for example?|||Thanks for the reply Hugo. (I don't usually multi-post, btw,
but...sorry.) Your solution works great, even though I didn't
accurately post my sample data (where M000251501 is followed by
M000001601).

And oh, if only I could redesign the table! Out of my control however
with this application <sigh>.

Thanks again,
-- Ian