Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Wednesday, March 28, 2012

How to remove non-Numeric or non-alphameric characters from a string in Sql Server 2005

Hi to all,

I am having a string like (234) 522-4342.

i have to remove the non numeric characters from the above string.

Please help me in this regards.

Thanks in advance.

M.ArulMani

Hi,

How about this:

Public Function StripAlpha(ByVal PassedStr)As String' ' Leaves only any numeric values in passed string 'Dim iAs Integer Dim GotCharAs Boolean Dim HoldStrAs String =""Dim HoldCharAs String =""'Clears Leading / trailing spaces PassedStr = Trim(PassedStr)' Cycle through the string to remove unwanted charactersFor i = 1To Len(PassedStr) HoldChar = Mid$(PassedStr, i, 1)If Not IsNumeric(HoldChar)Then GotChar =True Else GotChar =False End If If Not GotCharThen HoldStr = HoldStr & HoldCharEnd If Next i StripAlpha = HoldStrEnd Function

You just pass in something like StripAlpha("xyz()12345") and it should return just the numbers.

Hope this helps.

Paul

|||

Duplicate post. Please use the other thread if anyone would like to contribute:http://forums.asp.net/t/1111146.aspx

How to remove non-Numeric or non-alphameric characters from a string in Sql Server 2005

Hi to all,

I am having a string like (234) 522-4342.

i have to remove the non numeric characters from the above string.

Please help me in this regards.

Thanks in advance.

M.ArulMani

Hi,

How about this:

Public Function StripAlpha(ByVal PassedStr)As String' ' Leaves only any numeric values in passed string 'Dim iAs Integer Dim GotCharAs Boolean Dim HoldStrAs String =""Dim HoldCharAs String =""'Clears Leading / trailing spaces PassedStr = Trim(PassedStr)' Cycle through the string to remove unwanted charactersFor i = 1To Len(PassedStr) HoldChar = Mid$(PassedStr, i, 1)If Not IsNumeric(HoldChar)Then GotChar =True Else GotChar =False End If If Not GotCharThen HoldStr = HoldStr & HoldCharEnd If Next i StripAlpha = HoldStrEnd Function

You just pass in something like StripAlpha("xyz()12345") and it should return just the numbers.

Hope this helps.

Paul

|||

Well I dont recommend looping through the string its better if you use Regular Expressions.

I have bloged about this here :http://dotnetolympians.wordpress.com/2007/01/25/trimming-a-string/

Regular expressions are faster and use lesser code all this above can be done in 1-2 lines of code :).

How To Remove Leading Zeros

Hi
I need to remove leading zeros from a text string of numbers. For example:-
'000012' needs to be '12'
'000123' needs to be '123'
'012345' needs to be '12345'
'008000' needs to be '8000'
'01203' needs to be '1203'
There can be between 1 and 4 zeros at the front of the string. Removing all
zeros is not difficult using String Functions, but I only need to remove the
leading zeros. Does anyone have any suggestions?
Thanksif there are no blanks in the original string, then try this:
select replace(ltrim(replace('001100120','0',' ')),' ','0')
BTW "text string of numbers" might be a database design flaw|||Here is a brute force method.
select replace(ltrim(replace('000012','0',' ')),' ','0')
select replace(ltrim(replace('000123','0',' ')),' ','0')
select replace(ltrim(replace('012345','0',' ')),' ','0')
select replace(ltrim(replace('008000','0',' ')),' ','0')
select replace(ltrim(replace('01203','0',' ')),' ','0')
Payson
andrew wrote:
> Hi
> I need to remove leading zeros from a text string of numbers. For example
:-
> '000012' needs to be '12'
> '000123' needs to be '123'
> '012345' needs to be '12345'
> '008000' needs to be '8000'
> '01203' needs to be '1203'
> There can be between 1 and 4 zeros at the front of the string. Removing a
ll
> zeros is not difficult using String Functions, but I only need to remove t
he
> leading zeros. Does anyone have any suggestions?
> Thanks|||Convert to int (if all the fields are numbers only of course)
declare @.value varchar(20)
select @.value ='000012'
select convert(int,@.value)
http://sqlservercode.blogspot.com/|||convert to int and back to varchar
e.g.
declare @.x table (col1 varchar(6))
insert into @.x
select '000012' union all
select '000123' union all
select '012345' union all
select '008000' union all
select '01203'
select convert(varchar, convert(int, col1)) as Stripped
from @.x
andrew wrote:
> Hi
> I need to remove leading zeros from a text string of numbers. For example
:-
> '000012' needs to be '12'
> '000123' needs to be '123'
> '012345' needs to be '12345'
> '008000' needs to be '8000'
> '01203' needs to be '1203'
> There can be between 1 and 4 zeros at the front of the string. Removing a
ll
> zeros is not difficult using String Functions, but I only need to remove t
he
> leading zeros. Does anyone have any suggestions?
> Thanks|||Thanks guys, some good ideas here - I'll try them out in the morning.
You may be right, Alex, about the design flaw, but it's not my database!
"Trey Walpole" wrote:

> convert to int and back to varchar
> e.g.
> declare @.x table (col1 varchar(6))
> insert into @.x
> select '000012' union all
> select '000123' union all
> select '012345' union all
> select '008000' union all
> select '01203'
> select convert(varchar, convert(int, col1)) as Stripped
> from @.x
>
> andrew wrote:
>|||Once again, thanks for the suggestions, guys. Just for the record,
converting to Integer data type seems the easiest way to go:
SELECT CAST(field_name AS int) AS alias FROM table_name
"andrew" wrote:
> Thanks guys, some good ideas here - I'll try them out in the morning.
> You may be right, Alex, about the design flaw, but it's not my database!
>
> "Trey Walpole" wrote:
>

Monday, March 26, 2012

How to Remove '-' from QAA -

Can someone help me with a query that removes the '-' from
as string QAA -
ThanksDo you mean something like this:
Select Left('QAA-',3)
"Disney" <Disney@.discussions.microsoft.com> wrote in message
news:FAEFEC69-13FE-43E4-A24E-1EB170CA3445@.microsoft.com...
> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>|||replace('QAA -', '-', '')
rtrim(replace('QAA -', '-', ''))
to get rid of any trailing spaces.
"Disney" <Disney@.discussions.microsoft.com> wrote in message
news:FAEFEC69-13FE-43E4-A24E-1EB170CA3445@.microsoft.com...
> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>|||hi
select left('qaa-',3)
--
thanks,
Jose de Jesus Jr. Mcp,Mcdba
Data Architect
Sykes Asia (Manila philippines)
MCP #2324787
"Disney" wrote:

> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>sql

Monday, March 12, 2012

How to read XML data from SQL data field?

Using RS2000

I have a field in a SQL DB which contains data stored as an XML string. Is there an easy way to parse this string into data without moving to SS2005?

I have builts a parser in SQL, but I would like to know if RS had a way to directly read this. If not, is there a method in RS2005 which handles this type of data?

The only way to really do this in RS2000 is to create your own custom data processing extension that encapsulates the code you have written to parse the Xml. There are quite a few examples online.

In RS2005, you can use the Xml Data Processing Extension, which is designed for retieving data from xml data sources. It retrieves the data from an xml document which is retireved from a web service, web page, or can use a document embedded in the Xml Query. This extension is very powerful, but can also be somewhat complex for advanced queries.

For more information: http://msdn2.microsoft.com/en-us/library/ms159741.aspx|||

you can write a function in report Code section that will take the xml string, load it into System.Xml.XmlDocument and parse it.

<?xml version="1.0" encoding="utf-8"?>

<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

<DataSources>

<DataSource Name="DataSource1">

<ConnectionProperties>

<IntegratedSecurity>true</IntegratedSecurity>

<ConnectString>server=.</ConnectString>

<DataProvider>SQL</DataProvider>

</ConnectionProperties>

<rd:DataSourceID>6cfe005e-c5e0-4297-aa6b-f2ca0673ec05</rd:DataSourceID>

</DataSource>

</DataSources>

<BottomMargin>1in</BottomMargin>

<RightMargin>1in</RightMargin>

<rd:DrawGrid>true</rd:DrawGrid>

<InteractiveWidth>8.5in</InteractiveWidth>

<rd:SnapToGrid>true</rd:SnapToGrid>

<Body>

<ReportItems>

<List Name="list1">

<Left>1.25in</Left>

<ReportItems>

<Textbox Name="my_xml_1">

<Left>0.5in</Left>

<Top>0.5in</Top>

<rd:DefaultName>my_xml_1</rd:DefaultName>

<Width>3.375in</Width>

<Style>

<PaddingLeft>2pt</PaddingLeft>

<PaddingBottom>2pt</PaddingBottom>

<PaddingRight>2pt</PaddingRight>

<PaddingTop>2pt</PaddingTop>

</Style>

<CanGrow>true</CanGrow>

<Height>0.25in</Height>

<Value>=Code.ParseXml(Fields!my_xml.Value)</Value>

</Textbox>

</ReportItems>

<DataSetName>DataSet1</DataSetName>

<Top>0.375in</Top>

<Height>1in</Height>

</List>

</ReportItems>

<Height>2in</Height>

</Body>

<rd:ReportID>c9ad02b9-b7a2-4780-b954-3ebaa11e0afb</rd:ReportID>

<LeftMargin>1in</LeftMargin>

<DataSets>

<DataSet Name="DataSet1">

<Query>

<rd:UseGenericDesigner>true</rd:UseGenericDesigner>

<CommandText>select '&lt;root&gt;Hello world!&lt;/root&gt;' my_xml

union select '&lt;root&gt;Goodbye!&lt;/root&gt;'</CommandText>

<DataSourceName>DataSource1</DataSourceName>

</Query>

<Fields>

<Field Name="my_xml">

<rd:TypeName>System.String</rd:TypeName>

<DataField>my_xml</DataField>

</Field>

</Fields>

</DataSet>

</DataSets>

<CodeModules>

<CodeModule>System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</CodeModule>

</CodeModules>

<Code>public shared Function ParseXml(xml as string) as string

Dim doc as System.Xml.XmlDocument = new System.Xml.XmlDocument()

doc.LoadXml(xml)

ParseXml = doc.SelectSingleNode("root").InnerText

end function</Code>

<Width>6.5in</Width>

<InteractiveHeight>11in</InteractiveHeight>

<Language>en-US</Language>

<TopMargin>1in</TopMargin>

</Report>

Friday, March 9, 2012

How to read third word from a string?

Hallow, everyone:
I want to read third word from a string. For example, the string is,
ABCDE fghijk 031 LPN OPQ
I need 031. How to read it?
Any help will be appreciated.
Thanks
ZYTOk, do I win a prize for finding the ugliest, most cumbersome way to do this? :)

declare @.strtest as varchar(100)
set @.strtest='ABCDE fghijk 031 LPN OPQ'
select substring(@.strtest,charindex(' ', @.strtest, charindex(' ',@.strTest,1)+1), charindex(' ', @.strtest,charindex(' ', @.strtest, charindex(' ',@.strTest,1)+1)+1)-charindex(' ', @.strtest, charindex(' ',@.strTest,1)+1))

Of course, it crashes if there are only three words to begin with.|||I'm sure there is an easier way..but here's my offering

DECLARE @.x varchar(8000)

SET @.x = 'ABCDE fghijk 031 LPN OPQ'

SELECT SUBSTRING(@.x
, CHARINDEX(' ',@.x,CHARINDEX(' ',@.x)+1)+1
, (CHARINDEX(' ',@.x,CHARINDEX(' ',@.x,CHARINDEX(' ',@.x)+1)+1)-1)
- (CHARINDEX(' ',@.x,CHARINDEX(' ',@.x)+1)+1)+1)|||I think you would have to add a space to the end of the string, just to make sure it always works, even if there are only 3 words.|||parsing strings is so much easier in compiled code. forgive me for saying this but sql sucks at it. what sql is good at is set based operations.

you should do this on the client if you can:

string[] s = mystring.Split(' ');
string third = s.Length >= 3 ? s[2] : null;|||that is what is listed in Inside T-SQL Programming as one of the justifications for implementing CLR and I looked over the performance metrics and played with it myself. but I am still of the mind that if it requires C# code do it in the application. we are prepping for the whole 2K5 thing, and one the things that scares me is the potential abuse that CLR leaves open. in sql 2k, i had to worry about bad sql which I could fix. Now I might have to worry about bad C# in my sql server process and it has been too long since I really programmed app code.|||that is what is listed in Inside T-SQL Programming as one of the justifications for implementing CLR and I looked over the performance metrics and played with it myself. but I am still of the mind that if it requires C# code do it in the application. we are prepping for the whole 2K5 thing, and one the things that scares me is the potential abuse that CLR leaves open. in sql 2k, i had to worry about bad sql which I could fix. Now I might have to worry about bad C# in my sql server process and it has been too long since I really programmed app code.

any technology can be abused. that's not necessarily a reason not to use it though. it can be a very powerful thing for stuff that sql is not designed for, such as string parsing or complicated math.

if you are not comfortable with C# or some other .net language though, I wouldn't recommend using CLR in sql server. why not learn it though? it's always good to grow. :)|||Here's so more abuse

CREATE FUNCTION udf_GetWord (
@.str nvarchar(4000)
, @.Word int
, @.Delim char(1)
)
RETURNS nvarchar(4000)
AS
BEGIN
DECLARE @.LastPosition int, @.DelimFound int, @.Start int, @.End int, @.WordFound nvarchar(4000)

SELECT @.LastPosition = 0, @.DelimFound = 0
WHILE (@.DelimFound < @.Word-1)
BEGIN
IF (CHARINDEX(@.Delim, @.str, @.LastPosition + 1) = 0)
BREAK

ELSE
BEGIN
SET @.LastPosition = CHARINDEX(@.Delim, @.str, @.LastPosition + 1)
SET @.DelimFound = @.DelimFound + 1
END

END

SET @.Start = @.LastPosition + 1
SET @.End = CHARINDEX(@.Delim, @.str, @.LastPosition + 1) - @.Start
IF @.End < 0 SET @.End = LEN(@.str)-@.start+1
SELECT @.WordFound = SUBSTRING(@.str,@.start,@.end)
RETURN @.WordFound
END|||any technology can be abused. that's not necessarily a reason not to use it though. it can be a very powerful thing for stuff that sql is not designed for, such as string parsing or complicated math.

if you are not comfortable with C# or some other .net language though, I wouldn't recommend using CLR in sql server. why not learn it though? it's always good to grow. :)

the average dba makes more than the average developer and no one is going to pay me to code C# right now. I actually spent the first few years of my programming career as a vb \ java \ classic asp developer but it has been all dba for a while now. lets see, should I take the entry level c# developer job with a paycut or should I take the good paying mid-level\senior dba job? hmmmmmm. I am only into my 2nd sql 2k5 book, so I am far enough behind in what I am decent at.|||I wasn't suggesting that you quit and start fresh as a dime-a-dozen programmer. just that you could learn C# if you wanted to. sounds like you don't want to though.

in that case stick with parsing strings in sql. it works, it's just not the most efficient way. ;)|||It's a front end issue...let the minions handle it|||I wasn't suggesting that you quit and start fresh as a dime-a-dozen programmer. just that you could learn C# if you wanted to. sounds like you don't want to though.

in that case stick with parsing strings in sql. it works, it's just not the most efficient way. ;)

I hear you but the only way to get good is to do it everyday and I just do not have that opp. I actually picked up Inside C# and got myself a compiler last summer and frankly I got bored with it.|||fair enough.

about getting bored though, i think that's your own fault (or maybe the books fault - I hardly ever read tech books), not the fault of the language. there are lots of interesting and fun things you can do in C/C++/C#.

Here's just one tiny example: implement an RDBMS. your beloved SQL Server is implemented in those languages. ;)

How to read the return value of a stored procedure?

Stored procedure in SQL Server 2K is as follows..

CREATE PROCEDURE TestDataRead

@.TestString varchar(20) OUTPUT

AS

SET @.TestString = 'Mr.String'

GO

--

SSIS package details.

OLEDB connection manager; Connection works fine.

Execute SQL Task Editor properties are as follows.

ResultSetàNone

SQLStatementà exec TestDataRead

SQLSourceTypeBig SmileirectInput

Parameter Mapping:

VariableName: selected the user variable from the list.

Direction: Output

DataType:varchar

Parameter Name: 0

Parameter Type: 20

When I run I am getting the following error.

SSIS package "TEST SSIS1.dtsx" starting.
Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "exec TestDataRead" failed with the following error: "Procedure 'TestDataRead' expects parameter '@.TestString', which was not supplied.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. ...........................................
...................................................................

Please help.

Smith

John Smith001 wrote:

SQLStatementà exec TestDataRead ? OUTPUT

For output parameters also it needs to be passed when calling the stored procedure.

Thanks

|||

Thank you, Karunakarana!

How to read return value from sqlpipe send(string) method

Hi guys,
How can i read in my C# client application values returned from sqlpipe send(string)/send(reader method from CLR stored procedure.....following is example of a stored procedure.I want to read datetime string in my C# client
Thanks
[Microsoft.SqlServer.Server.SqlProcedure]
public static void PrintToday()
{
// Put your code here
SqlPipe p;
p = SqlContext.Pipe;
p.Send(System.DateTime.Today.ToString());
}

Hi!

Execute your PrintToday with SqlCommand.ExecuteReader, then read the string from SqlDataReader returned.

|||Exactly how are you supposed to do this? No matter what i do, the reader is always empty.

How to read return value from sqlpipe send(string) method

Hi guys,
How can i read in my C# client application values returned from sqlpipe send(string)/send(reader method from CLR stored procedure.....following is example of a stored procedure.I want to read datetime string in my C# client
Thanks
[Microsoft.SqlServer.Server.SqlProcedure]
public static void PrintToday()
{
// Put your code here
SqlPipe p;
p = SqlContext.Pipe;
p.Send(System.DateTime.Today.ToString());
}

Hi!

Execute your PrintToday with SqlCommand.ExecuteReader, then read the string from SqlDataReader returned.

|||Exactly how are you supposed to do this? No matter what i do, the reader is always empty.

Wednesday, March 7, 2012

How to read contents of text file from t-sql ?

Hi friends,
I need to read content of text file and store them in
string variable in my store procedure, Is there t-sql or
function to read content of text file ?
Thanks.There is no direct set of functions to do it, but you could use the sp_OA*
set of procedures to access the file. For an example of how to use these
procedures see:
http://www32.brinkster.com/srisamp/sqlArticles/article_32.htm
--
HTH,
SriSamp
Please reply to the whole group only!
http://www32.brinkster.com/srisamp
"Kresna Rudy Kurniawan" <kresna_rk@.yahoo.com> wrote in message
news:081001c3a377$c35948b0$a601280a@.phx.gbl...
> Hi friends,
> I need to read content of text file and store them in
> string variable in my store procedure, Is there t-sql or
> function to read content of text file ?
>
> Thanks.

How to reach report variables from custom code

Hello,

I'd like to use Globals!ReportName and User!Language in custom code like this:

Function Localize(ByVal key As String) As String
Return ReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)
End Function

If I preview the report I get an error message saying that there is error on line 2 of custom code.
Is it possible to reach report variables in custom code?

Thanks!

Werner

I could try and guess what you are doing but chances are I wouldn't be close. Someone might be able to suggest something if you give the background/intention of using those two global reporting service parameters.|||Hello Mguvu,

sorry for replying so late, but I (almost) gave up on looking into the forum...

I'll elaborate on my problem/intentions:
I want to localize the output of textfields in my reports. As there is no assistance from the SSRS for this requirement, I wrote my own assembly which contains the following method:

public static string Localize(string reportName, string key, string language)

This method gets a localized string from a database for a given report, key and language (culture). In the report definition I'd like to shorten the call to this method to something like this

Code.Localize("myKeyValue")

For this to work, I'd need access to the global report variables "Globals!ReportName" and "User!Language" from custom code

Function Localize(ByVal key As String) As String
Return RemoteReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)
End Function

But this is not working....

werner

|||

You should be able to pass an instance of Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals to your function. No?

(I think that's the right class, it might not be)

>L<

|||Actually I have a working version of my custom code and it looks like this

Function Localize(ByVal report As String, ByVal key As String, ByVal language As String) As String
Return RemoteReportUtil.Localizer.Localize(report, key, language)
End Function

In my report definition I call it in the following way

Code.Localize(Globals!ReportName, "ReportType", User!Language)

This works just fine, but is a little to verbose for my taste. I'd really like to just write Code.Localize("ReportTitle") in my report definition and reference the "global report variables" Globals!ReportName and User!Language directly in my custom code:

Return RemoteReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)

But if I do this, the preview function of the report designer fails with the message:

An error occurred during local report processing.
The definition of the report '/Report' is invalid.
There is an error on line 2 of custom code:[BC30469] Reference to a non-shared member requires an object reference.

werner
|||

>>Actually...

It helps if you post your real question . And I'm not sure you have responded to my suggestion, which I do think will work for you, so I will elaborate.

These things are globals after all, they don't change for the life of the report. You should be able to initialize several variables with these values in the Report Code and never worry about them again.

I will illustrate by storing the information to a var up front, but you should be able to send this information into an instance of your class ONCE and have it forever.

1. I'm going to declare my instance of Global at the top of Code, like this:

Code Snippet

Public myGlobals AS Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals = Nothing

... your instance is not necessarily an instance of Globals, it could be an instance of your custom object that has a member of type Globals.

OK?

2. Now I have a function called Initialize(). In my example it looks like this:

Code Snippet

Public Function Initialize(ox AS Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals ) AS String
If IsNothing(myGlobals) Then
myGlobals = ox
End If
Return ""
End Function

... in your version it might instantiate your custom object and call a Set... function of that object, passing Globals, where it exists for future use. That is why I bothered with the ISNothing() check. I'm not sure if this would work, because I'm not trying it right now, so you could always use the same MyGlobals strategy I'm showing here.

3. Now you put this function in your page header, on any expression you like. IOW, one object at the top of the page gets to look like this:

Code Snippet

= Code.Initialize(Globals) & YourRealExpression

4. Now my Code Localize function can talk to myGlobals!ReportName, etc, and if you don't store such a reference to your custom object then it just passes on a reference to myGlobals!ReportName rather than Globals!ReportName.

You don't really need the VB Code function at all -- but if you really want to have it, you can have it say:

Code Snippet

Return RemoteReportUtil.Localizer.Localize(key, User!Language)

And in fact if you saved a a User reference during Initialize, or even just had another var that saved User!Language, as well as a Globals reference, your class' Localize function would only need one parameter...

5. Why I say that you don't need the VB Code function at all:

It might work just fine at this point to have your report expressions themselves look like this, with no intermediary :

Code Snippet

RemoteReportUtil.Localizer.Localize(Code.myGlobals!ReportName, "This key", Code.myUser!Language)

.. or some other variant, depending on what you've saved, such as:

RemoteReportUtil.Localizer.Localize(Code.myGlobals, "This key", Code.myUserLanguage)

... or, if you've got that object instantiated and initialized with its own global and user or global and language members, your report layout expressions only have to say:

Code Snippet

oRemoteReportUtil.Localizer.Localize("This key")

HTH,

>L<


|||Yes, now it works!
Thank you very much Lisa!

Regards,
werner
|||

You're welcome.

In general, though, if those are the only two items you need (report item and user language) I would just store those two string items, there's no real need to have access to the two objects repeatedly over the life of the report. Or you could pass the objects once to your custom object instance in Initialize and it could just store all the properties it could need, rather than the object itself. This seems more efficent and neater in terms of possible object cleanup.

>L<

How to reach report variables from custom code

Hello,

I'd like to use Globals!ReportName and User!Language in custom code like this:

Function Localize(ByVal key As String) As String
Return ReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)
End Function

If I preview the report I get an error message saying that there is error on line 2 of custom code.
Is it possible to reach report variables in custom code?

Thanks!

Werner

I could try and guess what you are doing but chances are I wouldn't be close. Someone might be able to suggest something if you give the background/intention of using those two global reporting service parameters.|||Hello Mguvu,

sorry for replying so late, but I (almost) gave up on looking into the forum...

I'll elaborate on my problem/intentions:
I want to localize the output of textfields in my reports. As there is no assistance from the SSRS for this requirement, I wrote my own assembly which contains the following method:

public static string Localize(string reportName, string key, string language)

This method gets a localized string from a database for a given report, key and language (culture). In the report definition I'd like to shorten the call to this method to something like this

Code.Localize("myKeyValue")

For this to work, I'd need access to the global report variables "Globals!ReportName" and "User!Language" from custom code

Function Localize(ByVal key As String) As String
Return RemoteReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)
End Function

But this is not working....

werner

|||

You should be able to pass an instance of Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals to your function. No?

(I think that's the right class, it might not be)

>L<

|||Actually I have a working version of my custom code and it looks like this

Function Localize(ByVal report As String, ByVal key As String, ByVal language As String) As String
Return RemoteReportUtil.Localizer.Localize(report, key, language)
End Function

In my report definition I call it in the following way

Code.Localize(Globals!ReportName, "ReportType", User!Language)

This works just fine, but is a little to verbose for my taste. I'd really like to just write Code.Localize("ReportTitle") in my report definition and reference the "global report variables" Globals!ReportName and User!Language directly in my custom code:

Return RemoteReportUtil.Localizer.Localize(Globals!ReportName, key, User!Language)

But if I do this, the preview function of the report designer fails with the message:

An error occurred during local report processing.
The definition of the report '/Report' is invalid.
There is an error on line 2 of custom code:[BC30469] Reference to a non-shared member requires an object reference.

werner
|||

>>Actually...

It helps if you post your real question . And I'm not sure you have responded to my suggestion, which I do think will work for you, so I will elaborate.

These things are globals after all, they don't change for the life of the report. You should be able to initialize several variables with these values in the Report Code and never worry about them again.

I will illustrate by storing the information to a var up front, but you should be able to send this information into an instance of your class ONCE and have it forever.

1. I'm going to declare my instance of Global at the top of Code, like this:

Code Snippet

Public myGlobals AS Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals = Nothing

... your instance is not necessarily an instance of Globals, it could be an instance of your custom object that has a member of type Globals.

OK?

2. Now I have a function called Initialize(). In my example it looks like this:

Code Snippet

Public Function Initialize(ox AS Microsoft.ReportingServices.ReportProcessing.ReportObjectModel.Globals ) AS String
If IsNothing(myGlobals) Then
myGlobals = ox
End If
Return ""
End Function

... in your version it might instantiate your custom object and call a Set... function of that object, passing Globals, where it exists for future use. That is why I bothered with the ISNothing() check. I'm not sure if this would work, because I'm not trying it right now, so you could always use the same MyGlobals strategy I'm showing here.

3. Now you put this function in your page header, on any expression you like. IOW, one object at the top of the page gets to look like this:

Code Snippet

= Code.Initialize(Globals) & YourRealExpression

4. Now my Code Localize function can talk to myGlobals!ReportName, etc, and if you don't store such a reference to your custom object then it just passes on a reference to myGlobals!ReportName rather than Globals!ReportName.

You don't really need the VB Code function at all -- but if you really want to have it, you can have it say:

Code Snippet

Return RemoteReportUtil.Localizer.Localize(key, User!Language)

And in fact if you saved a a User reference during Initialize, or even just had another var that saved User!Language, as well as a Globals reference, your class' Localize function would only need one parameter...

5. Why I say that you don't need the VB Code function at all:

It might work just fine at this point to have your report expressions themselves look like this, with no intermediary :

Code Snippet

RemoteReportUtil.Localizer.Localize(Code.myGlobals!ReportName, "This key", Code.myUser!Language)

.. or some other variant, depending on what you've saved, such as:

RemoteReportUtil.Localizer.Localize(Code.myGlobals, "This key", Code.myUserLanguage)

... or, if you've got that object instantiated and initialized with its own global and user or global and language members, your report layout expressions only have to say:

Code Snippet

oRemoteReportUtil.Localizer.Localize("This key")

HTH,

>L<


|||Yes, now it works!
Thank you very much Lisa!

Regards,
werner
|||

You're welcome.

In general, though, if those are the only two items you need (report item and user language) I would just store those two string items, there's no real need to have access to the two objects repeatedly over the life of the report. Or you could pass the objects once to your custom object instance in Initialize and it could just store all the properties it could need, rather than the object itself. This seems more efficent and neater in terms of possible object cleanup.

>L<

Friday, February 24, 2012

How to query?

In the following query, @.CusVenRefLike is a string entered by user, it is by default equal to '%' so that the query return all string when user enter nothing.

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE Customer.CustomerRef LIKE @.CusVenRefLike

I find that the resulting dataset contain ONLY rows that Voucher.CustomerID<>-1. The reason is that when Voucher.CustomerID= -1, Customer.CustomerRef=NULL which is not included in Customer.CustomerRef LIKE '%' filter.

How can I include those row with Voucher.CustomerID=-1?

Thanks

You need to add additional constraints to your query, depending on exactly how you want it to work.

A simple approach is to use Coalesce(CustomerRef, '' ) to force the null into an empty string. This allows the match to procede. In fact, if there is no special meaning to the CustomerRef being NULL you might want to add a default to the column.

If you want to include nulls in any search, then add Or CustomerRef Is Null to the Where clause. You could also add Or (CustomerRef Is Null and @.CusVenRefLike = '%').

|||

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE Customer.CustomerRef LIKE @.CusVenRefLike

or Customer.CustomerRef is null

|||

Can do it as this as well..

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE isnull(Customer.CustomerRef ,'') LIKE @.CusVenRefLike