Showing posts with label write. Show all posts
Showing posts with label write. Show all posts

Monday, March 26, 2012

multi keyword search SP

Is it possible to write a Stored Procedure that takes a string of
search keywords as argument and returns the recordset? At the mo I am
passing the WHERE String as argument.

I got this technique from an Extreme Ultradev tutorial by Rick Curtis
it looked quite ok:
http://www.princeton.edu/~rcurtis/u...tutorial12.html

I have to admit, one of the main reason for passing the WHERE string is
that I do not know how to do the string splitting / parsing and putting
together in a Stored Procedure. I bet T-SQL would be just as powerful
as VBScript if I just knew it well enough.

What I liked about having built them on the web script was the
flexibility allowing to potentially build an advanced search without
having to change the stored procedure - but this is not crucial I could
always write several stored procedures or add parameters to the SP.

Here is what I have achieved in this way:
User can enter one ore more keywords separated by space.
Search algorithm returns results across a number of fields where ALL
search words are contained in any of these.
Search results will always be formatted a certain way and displayed in
a html table no matter how the search procedure / criteria is varied.

Here is the algorithm (that now works in ASP)
1. split search string into separate keywords
2. build where condition based on single keyword, concatenating all
searched fields (" AND f1+' '+f2+{' '+f<n>} LIKE %<keyword>%")
3. concatenate all these where conditions and pass to stored procedure.
4. stored procedure takes care of all other logic (e.g. Joins, which
fields are searched etc.). It uses a string variable @.SQL to build the
complete search string and then does
execute (@.SQL);
to create the recordset.

I bet there is a way to move 1. 2. and 3. into the SP (and I would feel
better if it was) but I don't have the expertise to do this. If anybody
wants to help me this is very welcome.

I can also post my original code to clarify, just want to avoid too
long posts.

Cheers
AxelThese links might give you some ideas (the first is similar to the
article you linked to, but from a pure TSQL perspective):

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

TSQL string functions are not as powerful as those in other languages,
so if you have lots of string parsing, it would probably be best to do
it in the ASP code rather than in TSQL.

If your requirements become more complex, you could consider some sort
of reporting tool, rather than writing and maintaining code yourself.

Simon|||Thanks Simon

I had actually already read that article but it takes a different
approach - the SP takes a named list of parameters (similar to an
advanced search form) so it presumes the user knows where to look for
the keyword. My approch concatenates all candidate fields into one
large string and then looks for the search string within that long
string. It loops this process with multilpe kewoards and concatenates
using the AND condition.

If for example we assume for simplicities sake there is on table
tblProduct with the fields Name, Desc, Comment, Category, ID and I have
a record with "Iron Screw", "17 inch amalgated Screw - green", "useful
for outdoor use","consumables","1234-23"
this would be caught by passing "screw iron 17 outdoor" to the search
procedure. The user does not need to know in which fields the keywords
are contained but at the same time he will be able to narrow down the
search results very efficiently by adding more search words.
In my little loop I am comparing
'Iron Screw 17 inch amalgated Screw - green useful for outdoor use
consumables 1234-23' Like '%screw%'
AND
'Iron Screw 17 inch amalgated Screw - green useful for outdoor use
consumables 1234-23' Like '%iron%'
AND
'Iron...' Like '%17%'
AND
'Iron...' Like '%outdoor%'

what I need is like a split() and loop in T-SQL; also I would have to
eliminate invalid characters e.g. single quotes for the search string
to avoid any attempts at hacking.

I was told using dynamic SQL the way I have done here is wrong I only
want to get it right. Maybe there is another approach? MOre opinions
welcome...

thx,
Axel|||On 17 Jun 2005 03:56:57 -0700, Axel wrote:

>My approch concatenates all candidate fields into one
>large string and then looks for the search string within that long
>string.
(snip example)

Hi Axel,

The example clarifies what you want to do.

First, revisit this page: http://www.sommarskog.se/arrays-in-sql.html.
It will explain how you can break the collected search words ("screw
iron 17 outdoor" in your example) into a set of rows.

To find the Products that match at least one of the terms given, use

SELECT DISTINCT p.Product
FROM Products AS p
INNER JOIN #SearchWords AS s-- The search words in a table;
-- See link above for details.
ON p.Name + p.Desc + p.Comment + p.Category + p.ID
LIKE '%' + s.Word + '%'

And if you only want the products that match ALL the terms given:

SELECT p.Product
FROM Products AS p
INNER JOIN #SearchWords AS s-- The search words in a table;
-- See link above for details.
ON p.Name + p.Desc + p.Comment + p.Category + p.ID
LIKE '%' + s.Word + '%'
GROUP BY p.Product
HAVING COUNT(*) = (SELECT COUNT(*) FROM #SearchWords)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Axel (realraven2000@.hotmail.com) writes:
> I had actually already read that article but it takes a different
> approach - the SP takes a named list of parameters (similar to an
> advanced search form) so it presumes the user knows where to look for
> the keyword. My approch concatenates all candidate fields into one
> large string and then looks for the search string within that long
> string. It loops this process with multilpe kewoards and concatenates
> using the AND condition.

If I were you, I would look into full-text search. Not that I know
whether this is the answer to your problem, because I have never
used full-text myself. But I would look into it, before I started
to build a complex engine myself.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Friday, March 23, 2012

Mulitple Update in mYSQL

I need to write a query to update two mysql tables simultaneously ie:
i have two tables:
Table1 and Table2.
and each of the these tables have a realting field... So i tried writing a update query this way.

Update TABLE1,TABLE2 SET TABLE1.field1 = 'aaaa' , TABLE2.field1='bbb' Where TABLE1.field2 = 12 and TABLE1.field1=TABLE2.field1

But this query showed me an error.. i can do this breaking into 2 queries, but i want it to be done in one single go... any idea on this??

Thanking you in advance..Originally posted by nikks525
I need to write a query to update two mysql tables simultaneously ie:
i have two tables:
Table1 and Table2.
and each of the these tables have a realting field... So i tried writing a update query this way.

Update TABLE1,TABLE2 SET TABLE1.field1 = 'aaaa' , TABLE2.field1='bbb' Where TABLE1.field2 = 12 and TABLE1.field1=TABLE2.field1

But this query showed me an error.. i can do this breaking into 2 queries, but i want it to be done in one single go... any idea on this??

Thanking you in advance..
I don't use MySQL but updating 2 tables in one statement is not allowed generally in SQL. One way to achieve something like it (in Oracle at least) is to create a view for the join query with an INSTEAD OF UPDATE trigger. So the user can update one view, and the trigger actually updates 2 tables. I don't know if MySQL supports INSTEAD OF triggers, though.

Why do you want to do it anyway? Is it just a covenience issue or do you have some other reason for not wanting to perform 2 updates?|||I just noticed this before replying to the same thread in the MySQL forum. Simple answer; to the best of my knowledge, you can't. It's not valid SQL. And to extend my learned chum andrewst's comments, MySQL doesn't support triggers or views so no go there I'm afraid.

I'm also intrigued as to why you need to do this?|||I just wanted to do a easy job with writing the update in a single query.. rather than 2 different queries..
yea i think it needs to be broken up into 2 different Queries ..

anyway thanks for your replies ..|||Originally posted by andrewst
I don't use MySQL but updating 2 tables in one statement is not allowed generally in SQL. One way to achieve something like it (in Oracle at least) is to create a view for the join query with an INSTEAD OF UPDATE trigger. So the user can update one view, and the trigger actually updates 2 tables. I don't know if MySQL supports INSTEAD OF triggers, though.

Why do you want to do it anyway? Is it just a covenience issue or do you have some other reason for not wanting to perform 2 updates?

CAN U PLEASE LET ME KNOW HOW TO CREATE VIEWS IN MYSQL TO UPDATE 2 TABLES IN MYSQL|||No need to shout :p

It's been a while since I checked up with developments over at MySQL AB but (see my post above) as far as I know, you can't. No triggers, no updateable views and transaction support only in certain table types.

Why can't you fire off two update statements?

(caveat: I'm quite happy to have my comments above proven wrong by someone more up-to-date on the latest MySQL releases)

Friday, March 9, 2012

MSSQL's Design View is 4 LAZY CODERS (LOSERS)

I'd just like to say to all you lazy donks out there who can't
"write" a query without the damn design viewer have made my life,
and I'm sure countless others, a perpetual annoyance! Is it so hard
to sit down and write nice and clean queries yourself? Think of how
many hours over a period of a couple months you could save your
co-workers when they have to debug your crap (yes givler/rusnak, your
shit is that bad) if you quit copying and pasting that horribly
formatted SQL code from that damn thing and actually WROTE IT YOURSELF!
I don't mind so much fixing your ill conceived design view
adventures, it's that I have to sit down and read the stuff later and
it's a jumbled concoction of pure laziness! Hell, you can't even
write nicely formatted code when you DO write it yourself you lazy
oafs. I NEVER use that damn thing and my SQL code is always
pretty-formatted and efficient, as you have been fond of noticing.
THUFPPPPTTTT!!!!! jerks
Thanks,
Parlous2112Everybody knows that, who are you talking to ?|||I was just blowing off steam here and giving fair warning to anyone I
may encounter in the future if I discover their nasty little secret -
BEWARE OF PARLOUS2112! This way, I don't have to murder any co-workers
:).|||Maybe you can post some of them here:
http://www.thedailywtf.com/
ML|||Just post a google link to this thread.
"ML" <ML@.discussions.microsoft.com> wrote in message
news:88993E30-BC4F-4932-BC47-188236BD76E9@.microsoft.com...
> Maybe you can post some of them here:
> http://www.thedailywtf.com/
>
> ML|||:) Evil.
ML

Monday, February 20, 2012

MSSQL Nested queries

Hi,

I have been trying to write a nested query, however i am facing errors while executing that.

The code is as below.

<%

Dim MyConnection =New SqlConnection()

MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("AppConnectionString1").ConnectionString

MyConnection.Open()

Dim cmdAsNew SqlCommandDim rsAs SqlDataReaderDim rs2As SqlDataReaderDim query ="select count(bank_id) from bank_master"Dim query2AsString

cmd.CommandType = CommandType.Text

cmd.Connection = MyConnection

cmd.CommandText = queryrs = cmd.ExecuteReaderIf rs.Read()ThenDim rec = rs(0)If (rec > 0)Then

Response.Write(rec &

" banks registered in the system")rs.Close()

query2 ="select * from bank_master order by bank_id"

rs2 = cmd.ExecuteReader(query2)

If rs2.Read()Then

Response.Write(rs2(0))

Else

Response.Write(

"No banks yet registered in the system")EndIfElse

Response.Write(

"No banks yet registered in the system")EndIfEndIf

%>

The error message that i am getting at runtime:

Server Error in '/Accounts' Application.

Input string was not in a correct format.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.FormatException: Input string was not in a correct format.

Source Error:

Line 117: Line 118: query2 = "select * from bank_master order by bank_id"Line 119: rs2 = cmd.ExecuteReader(query2)Line 120: If rs2.Read() ThenLine 121: Response.Write(rs2(0))


Source File:E:\WEBHOME\Accounts\bank.aspx Line:119

Could you please help?

Best Regards,

Debashis

Hi Debashis,

It looks to me like the problem may be that you don't have the line:

cmd.CommandText = query2

So you could have your code like:

 Dim MyConnection =New SqlConnection() MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("AppConnectionString1").ConnectionString MyConnection.Open()Dim cmdAs New SqlCommandDim rsAs SqlDataReaderDim rs2As SqlDataReaderDim queryAs String ="select count(bank_id) from bank_master"Dim query2As String ="select * from bank_master order by bank_id" cmd.CommandType = CommandType.Text cmd.Connection = MyConnection cmd.CommandText = query rs = cmd.ExecuteReaderIf rs.Read()Then Dim rec = rs(0)If (rec > 0)Then Response.Write(rec &" banks registered in the system") rs.Close() cmd.CommandText = query2 rs2 = cmd.ExecuteReader()If rs2.Read()Then Response.Write(rs2(0))Else Response.Write("No banks yet registered in the system")End If Else Response.Write("No banks yet registered in the system")End If End If

I haven't actually tried this code yet, but if this doesn't work, you could try having a cmd2 instead of re-using the single cmd line. I'm also not too sure why you need to run two queries as you could try this instead (unless I missed something Smile ):

 Dim resultAs Integer = 0' Initialise connectionDim MyConnection =New SqlConnection(ConfigurationManager.ConnectionStrings("AppConnectionString1").ConnectionString)' Initialise commandDim cmdAs SqlCommand =New SqlCommand() cmd.Connection = MyConnection cmd.CommandText ="select count(bank_id) from bank_master"' Execute command Using MyConnection result =CType(cmd.ExecuteScalar(),Integer)End UsingIf result > 0Then Response.Write(result &" banks registered in the system")Else Response.Write("No banks yet registered in the system")End If

Hope this helps.

All the best,

Paul

|||

Hi Peter,

Hi Peter,
Thanks for your reply. It seems to be working with: cmd.CommandText = query2
However I am still unable to workout the recordcount from the query, as it returns -1.
The code is:

query2 = "select * from bank_master order by bank_id"
cmd2.CommandType = CommandType.Text
cmd2.Connection = MyConnection
cmd2.CommandText = query2
rs2 = cmd2.ExecuteReader
If rs2.HasRows Then

%>
<table>
<%
While rs2.Read()
%>
<tr>
<td>
<%=rs2(1)%>
</td>
</tr>
<%
End While
%>
</table>
<%
Else
Response.Write("No banks yet registered in the system")
End If

Please note that I havent included the recordcount code, as it wrong!

Thanks

Debashis

|||

Hi Debashis,

Sorry, I had missed a line from my code:

Dim resultAs Integer = 0' Initialise connectionDim MyConnection =New SqlConnection(ConfigurationManager.ConnectionStrings("AppConnectionString1").ConnectionString)' Initialise commandDim cmdAs SqlCommand =New SqlCommand() cmd.Connection = MyConnection cmd.CommandText ="select count(bank_id) from bank_master"' Execute command Using MyConnectionMyConnection.open() result =CType(cmd.ExecuteScalar(),Integer)End UsingIf result > 0Then Response.Write(result &" banks registered in the system")Else Response.Write("No banks yet registered in the system")End If

I've tested it this time and is fine. The other code I gave you also worked, but because there was an extra If ... End if statement than necessary, it also puts the id of the last bank at the end of the line 'banks registered in the system'. therefore, going back to your original code, this also works:

Imports System.DataImports System.Data.SqlClientPartialClass BankInherits System.Web.UI.PageProtected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadDim MyConnection =New SqlConnection() MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("AppConnectionString1").ConnectionString MyConnection.Open()Dim cmdAs New SqlCommandDim rsAs SqlDataReaderDim queryAs String ="select count(bank_id) from bank_master" cmd.CommandType = CommandType.Text cmd.Connection = MyConnection cmd.CommandText = query rs = cmd.ExecuteReaderIf rs.Read()Then Dim recAs Integer = Convert.ToInt32(rs(0))If (rec > 0)Then Response.Write(rec &" banks registered in the system")Else Response.Write("No banks yet registered in the system")End If rs.Close()End If End SubEnd Class 
I put this code in the Page_Load event, and ran it OK.
If this has resolved the issue, please don't forget to mark it as the Answer.
Hope it helps,
Paul (not PeterSmile !)
|||

Hi Paul,

Apologies for the mistake.

It seems to be working fine. Thanks for the help..