Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Sunday, March 25, 2012

Best Query/Search Method

Hi,

I'm wondering about the following:

I have come across an InfoPath Forms application who's code is scripted in javascript and who's data seems to be in XML files.
An analyst at that company told me they suspect the data is ALSO in SQL Server... somewhere. They can't seem to find it though. I have
reviewed the .js code and some methods are called for which I can find no source. I believe those methods execute OK because they're found
inside some DLL.

I'm thinking I would enter a new record using the form in InfoPath using some datavalue that I can expect will be unique.. like a lastname who's first three chars is ZZZ or something like that. Subsequently, I'd search each column in each table in each DB on the server to see if I can locate it somewhere.

So, my question is what is the best approach for this? I have access to the db, table and column names. I know I can write a small vb.net piece of code to execute my search. But, is there some better way using some sql procedure (or using the full text catalog) instead or any other tool(s)?

Thanks in advance for your advise.

Stewart

Go into sql server management studio and open up a new query window, then set the query window to the the database in question.

Execute this query:

select 'union select ''[' + colu.table_schema + '].[' + colu.table_name + '].[' + colu.column_name + ']'' as "Schema.Table.Column" '
+ ',[' + colu.column_name + '] as "Value" '
+ ' from [' + colu.table_schema + '].[' + colu.table_name + '] '
+ ' where [' + colu.column_name + '] like ''ZZZ%'' '
from INFORMATION_SCHEMA.columns as colu
where colu.data_type in ('varchar','nvarchar','char','nchar','text','ntext')

Below the query will be the results, one sql statement per text-based column.

You can click, then right-click on the top-left button-looking box in the grid header and copy the text into the buffer.

Paste it into a new query window.

Delete the first "union" on the first line and execute the query.

It will return one row per column value per table that matches ZZZ%.

Depending upon the number of tables/columns in the database, and the number of rows in the table, you might need to split the results into multiple, smaller queries.


Enjoy!


|||

Hi David,

Thanks very much for the assistance. It worked perfectly!

Regards,
Stewart

|||

The views in the master database are very powerful. Try the information_schema views first, and switch to the sys... views if the information_schema views don't have what you need.

Glad it helped!

sql

Best Query Strategy

I am faced with the need to query the price of parts from a 3 table join.
The problem is the number of parts that need to be queried at one time; 10 t
o
100 parts. That would make for a very messy WHERE clause. I am wonder if
there is a better strategy?
If it matters, I am using VB.NET.
Thanks
--Rob
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...server/200510/1Robin,
Are the parts PART OF a larger organizational unit i.e., a project or a
company or...?
HTH
Jerry
"Robin H via droptable.com" <u4108@.uwe> wrote in message
news:5655fd7d2e20a@.uwe...
>I am faced with the need to query the price of parts from a 3 table join.
> The problem is the number of parts that need to be queried at one time; 10
> to
> 100 parts. That would make for a very messy WHERE clause. I am wonder if
> there is a better strategy?
> If it matters, I am using VB.NET.
> Thanks
> --Rob
>
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forum...server/200510/1|||Robin,
Is it possible you could do a VIEW for this as long as the query is not
dynamic?
Shahryar
Robin H via droptable.com wrote:

>I am faced with the need to query the price of parts from a 3 table join.
>The problem is the number of parts that need to be queried at one time; 10
to
>100 parts. That would make for a very messy WHERE clause. I am wonder if
>there is a better strategy?
>If it matters, I am using VB.NET.
>Thanks
>--Rob
>
>
Shahryar G. Hashemi | Sr. DBA Consultant
InfoSpace, Inc.
601 108th Ave NE | Suite 1200 | Bellevue, WA 98004 USA
Mobile +1 206.459.6203 | Office +1 425.201.8853 | Fax +1 425.201.6150
shashem@.infospace.com | www.infospaceinc.com
This e-mail and any attachments may contain confidential information that is
legally privileged. The information is solely for the use of the intended
recipient(s); any disclosure, copying, distribution, or other use of this in
formation is strictly prohi
bited. If you have received this e-mail in error, please notify the sender
by return e-mail and delete this message. Thank you.

Best Query Strategy

I am faced with the need to query the price of parts from a 3 table join.
The problem is the number of parts that need to be queried at one time; 10 to
100 parts. That would make for a very messy WHERE clause. I am wonder if
there is a better strategy?
If it matters, I am using VB.NET.
Thanks
--Rob
Message posted via droptable.com
http://www.droptable.com/Uwe/Forums...erver/200510/1
Robin,
Are the parts PART OF a larger organizational unit i.e., a project or a
company or...?
HTH
Jerry
"Robin H via droptable.com" <u4108@.uwe> wrote in message
news:5655fd7d2e20a@.uwe...
>I am faced with the need to query the price of parts from a 3 table join.
> The problem is the number of parts that need to be queried at one time; 10
> to
> 100 parts. That would make for a very messy WHERE clause. I am wonder if
> there is a better strategy?
> If it matters, I am using VB.NET.
> Thanks
> --Rob
>
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forums...erver/200510/1
|||Robin,
Is it possible you could do a VIEW for this as long as the query is not
dynamic?
Shahryar
Robin H via droptable.com wrote:

>I am faced with the need to query the price of parts from a 3 table join.
>The problem is the number of parts that need to be queried at one time; 10 to
>100 parts. That would make for a very messy WHERE clause. I am wonder if
>there is a better strategy?
>If it matters, I am using VB.NET.
>Thanks
>--Rob
>
>
Shahryar G. Hashemi | Sr. DBA Consultant
InfoSpace, Inc.
601 108th Ave NE | Suite 1200 | Bellevue, WA 98004 USA
Mobile +1 206.459.6203 | Office +1 425.201.8853 | Fax +1 425.201.6150
shashem@.infospace.com | www.infospaceinc.com
This e-mail and any attachments may contain confidential information that is legally privileged. The information is solely for the use of the intended recipient(s); any disclosure, copying, distribution, or other use of this information is strictly prohi
bited. If you have received this e-mail in error, please notify the sender by return e-mail and delete this message. Thank you.

Best Query Strategy

I am faced with the need to query the price of parts from a 3 table join.
The problem is the number of parts that need to be queried at one time; 10 to
100 parts. That would make for a very messy WHERE clause. I am wonder if
there is a better strategy?
If it matters, I am using VB.NET.
Thanks
--Rob
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200510/1Robin,
Are the parts PART OF a larger organizational unit i.e., a project or a
company or...?
HTH
Jerry
"Robin H via SQLMonster.com" <u4108@.uwe> wrote in message
news:5655fd7d2e20a@.uwe...
>I am faced with the need to query the price of parts from a 3 table join.
> The problem is the number of parts that need to be queried at one time; 10
> to
> 100 parts. That would make for a very messy WHERE clause. I am wonder if
> there is a better strategy?
> If it matters, I am using VB.NET.
> Thanks
> --Rob
>
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200510/1|||Robin,
Is it possible you could do a VIEW for this as long as the query is not
dynamic?
Shahryar
Robin H via SQLMonster.com wrote:
>I am faced with the need to query the price of parts from a 3 table join.
>The problem is the number of parts that need to be queried at one time; 10 to
>100 parts. That would make for a very messy WHERE clause. I am wonder if
>there is a better strategy?
>If it matters, I am using VB.NET.
>Thanks
>--Rob
>
>
Shahryar G. Hashemi | Sr. DBA Consultant
InfoSpace, Inc.
601 108th Ave NE | Suite 1200 | Bellevue, WA 98004 USA
Mobile +1 206.459.6203 | Office +1 425.201.8853 | Fax +1 425.201.6150
shashem@.infospace.com | www.infospaceinc.com
This e-mail and any attachments may contain confidential information that is legally privileged. The information is solely for the use of the intended recipient(s); any disclosure, copying, distribution, or other use of this information is strictly prohibited. If you have received this e-mail in error, please notify the sender by return e-mail and delete this message. Thank you.

Best program for SQL database manipulation

Hello All

I am a relative beginner to SQL databases & new to this forum, so please bear with me if my query is too basic and advise if this question belongs somewhere else

I began working at a company that uses a program that stores data in an SQL database running off a Firebird engine

The program itself doesnt come with database management/administration module, so I'll need to use an external program for manipulating data in the tables that the database contains.

I have relatively little knowledge in SQL programming, which is why I would like to know which is the most powerful program for SQL database updating / manipulation?

This database has tables that has an infinite number of joins with other tables - Even MS Access wasnt able to open a few tables in this database because of the number of joins. I have tried Access & Lotus Approach, Approach manages to do a better job than Access, it open the tables & seems like it will let me import external data directly into the SQL table, but takes forever & usually just bums out giving an error after a very long wait..

My question is - Apart from Access & Approach, are there any more powerful, yet user friendly programs out there that can help me update data directly into SQL tables? What options do I have - the tasks I need to perform are pretty simple updating & cleaning of data already in there

Please, I will hugely appreciate any pointers that you guys the experts might have for me in this regard

Thanks
AlexTry Microsoft SQL Server 2005 Express. It's Free & Downloadable From http://msdn.microsoft.com/vstudio/express/sql/sql

Best practise to provide non-DBAs querying capabilities in SQL200

When we used SQLServer 2000, we installed just query analyzer on desktops of
several of our IT folks so they could query data easily. Some of these folks
have admin priv for non-DBA reasons. Now that querying data is integrated
into the SQL 2005 management studio I am not sure the best way to provide
this function to these users. I don't want to give the full management
studio, especially to those with Admin but no appreciation for DBA tasks.
Any thoughts would be appreciated.
Thanks
--
FloraPerhaps QALite work against 2005?
http://rac4sql.net/qalite_main.asp
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Flora Seymour" <FloraSeymour@.discussions.microsoft.com> wrote in message
news:66C0EC4F-ACDB-47DB-9417-5258409A9584@.microsoft.com...
> When we used SQLServer 2000, we installed just query analyzer on desktops of
> several of our IT folks so they could query data easily. Some of these folks
> have admin priv for non-DBA reasons. Now that querying data is integrated
> into the SQL 2005 management studio I am not sure the best way to provide
> this function to these users. I don't want to give the full management
> studio, especially to those with Admin but no appreciation for DBA tasks.
> Any thoughts would be appreciated.
> Thanks
> --
> Flora|||Thanks - I'd rather stay within the MS SQL Server2005 product if possible,
but QALite may do the trick if I that does not work out. The info I found
on it does not mention SQL2005 , just SQL2000, SQL Server7. Any experience
with QALite on SQL2005?
--
Flora
"Flora Seymour" wrote:
> When we used SQLServer 2000, we installed just query analyzer on desktops of
> several of our IT folks so they could query data easily. Some of these folks
> have admin priv for non-DBA reasons. Now that querying data is integrated
> into the SQL 2005 management studio I am not sure the best way to provide
> this function to these users. I don't want to give the full management
> studio, especially to those with Admin but no appreciation for DBA tasks.
> Any thoughts would be appreciated.
> Thanks
> --
> Flora|||I haven't used QALite myself, but since the Query Analyzer (2000 version) work against 2005 (almost
all things), I think there's a good chance that QALite does as well.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Flora Seymour" <FloraSeymour@.discussions.microsoft.com> wrote in message
news:7E6DFEA1-4E1A-407C-938A-07EDB894F066@.microsoft.com...
> Thanks - I'd rather stay within the MS SQL Server2005 product if possible,
> but QALite may do the trick if I that does not work out. The info I found
> on it does not mention SQL2005 , just SQL2000, SQL Server7. Any experience
> with QALite on SQL2005?
> --
> Flora
>
> "Flora Seymour" wrote:
>> When we used SQLServer 2000, we installed just query analyzer on desktops of
>> several of our IT folks so they could query data easily. Some of these folks
>> have admin priv for non-DBA reasons. Now that querying data is integrated
>> into the SQL 2005 management studio I am not sure the best way to provide
>> this function to these users. I don't want to give the full management
>> studio, especially to those with Admin but no appreciation for DBA tasks.
>> Any thoughts would be appreciated.
>> Thanks
>> --
>> Flora

Best practise to provide non-DBAs querying capabilities in SQL200

When we used SQLServer 2000, we installed just query analyzer on desktops of
several of our IT folks so they could query data easily. Some of these folks
have admin priv for non-DBA reasons. Now that querying data is integrated
into the SQL 2005 management studio I am not sure the best way to provide
this function to these users. I don't want to give the full management
studio, especially to those with Admin but no appreciation for DBA tasks.
Any thoughts would be appreciated.
Thanks
--
FloraPerhaps QALite work against 2005?
http://rac4sql.net/qalite_main.asp
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Flora Seymour" <FloraSeymour@.discussions.microsoft.com> wrote in message
news:66C0EC4F-ACDB-47DB-9417-5258409A9584@.microsoft.com...
> When we used SQLServer 2000, we installed just query analyzer on desktops
of
> several of our IT folks so they could query data easily. Some of these fol
ks
> have admin priv for non-DBA reasons. Now that querying data is integrated
> into the SQL 2005 management studio I am not sure the best way to provide
> this function to these users. I don't want to give the full management
> studio, especially to those with Admin but no appreciation for DBA tasks.
> Any thoughts would be appreciated.
> Thanks
> --
> Flora|||Thanks - I'd rather stay within the MS SQL Server2005 product if possible,
but QALite may do the trick if I that does not work out. The info I found
on it does not mention SQL2005 , just SQL2000, SQL Server7. Any experience
with QALite on SQL2005?
Flora
"Flora Seymour" wrote:

> When we used SQLServer 2000, we installed just query analyzer on desktops
of
> several of our IT folks so they could query data easily. Some of these fol
ks
> have admin priv for non-DBA reasons. Now that querying data is integrated
> into the SQL 2005 management studio I am not sure the best way to provide
> this function to these users. I don't want to give the full management
> studio, especially to those with Admin but no appreciation for DBA tasks.
> Any thoughts would be appreciated.
> Thanks
> --
> Flora|||I haven't used QALite myself, but since the Query Analyzer (2000 version) wo
rk against 2005 (almost
all things), I think there's a good chance that QALite does as well.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Flora Seymour" <FloraSeymour@.discussions.microsoft.com> wrote in message
news:7E6DFEA1-4E1A-407C-938A-07EDB894F066@.microsoft.com...[vbcol=seagreen]
> Thanks - I'd rather stay within the MS SQL Server2005 product if possible
,
> but QALite may do the trick if I that does not work out. The info I fou
nd
> on it does not mention SQL2005 , just SQL2000, SQL Server7. Any experience
> with QALite on SQL2005?
> --
> Flora
>
> "Flora Seymour" wrote:
>

Monday, March 19, 2012

Best practice to pull data from sql server 2000 to sql server 2005 with dynamic queries

Hi There,

I need to pull data using input from one table in sql server 2005. I have to query against the sql server 2000 database and pull data into sql server 2005. I have a list of ids that I have to pass to a query to get the desired data. What is the best practice for this. Can I use SSIS or do I need to build an app in C#? Can somebody please reply back?

Thanks a lot!!

If you need to query sql server 2000 database to migrate data, then sql server 2005 import/export wizard might be a good one. Please take a look at http://msdn2.microsoft.com/en-us/library/ms141209.aspx. If you don't need to do query, bcp utility might be a good candidate. Please take a look at http://msdn2.microsoft.com/en-us/library/ms162802.aspx.

Thanks,

Junfeng

|||

First, set up the SQL 2000 server as a 'Linked Server' for the SQL 2005 server (See Books Online for details about Linked Servers.)

Then, using 'four-part naming conventions', you can just query between the two servers.

This example, when executed on the SQL 2005 server, would take data from the SQL 2000 server and insert it into the SQL 2005 server:


Code Snippet


INSERT INTO MyTable (Col1, Col2, Col3, etc.)
SELECT Col1, Col2, Col3, etc.
FROM MySQL2000Server.MyDatabase.dbo.MyTable
WHERE MyID IN ( 1, 2, 5, 10, 25 )

|||

Hi There,

Here's my requirements...

I have to run a query B against database B with results (list of ids) from a query A run against database A and then push the results back to database A. Query B is constructed dynamically from the results obtained from Query A. So I wouldlike to know what would be the best way to achive this?

Thanks a lot!!

Thursday, March 8, 2012

Best practice

i have two databases on two different servers, one which is a live server.
What i want to do is run a query to update a table in the second server wit
h
records from the first database. would this be a select if not exists ?It can be an insert followed by a subquery which is based on a NOT exists, a
ssuming that you want to
add the rows that doesn't exist (based on some key column).
Or, it can be an update based on a JOIN (or an update with a number of corre
lated subqueries in SET,
as well as an EXISTS), if you want to update rows that already exists in the
other table, picking
column values from that other table.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Peter Newman" <PeterNewman@.discussions.microsoft.com> wrote in message
news:B13DDBFC-4697-4DA6-B9C0-5F7A575BC8DF@.microsoft.com...
>i have two databases on two different servers, one which is a live server.
> What i want to do is run a query to update a table in the second server w
ith
> records from the first database. would this be a select if not exists ?
>

Wednesday, March 7, 2012

Best Performance Query

Hi:

I have the following query, can somebody help me?

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r ON s.Id = r.Id
WHERE
'1526858' BETWEEN FromTelephone AND ToTelephone

Where the '1526858' is a phone number.

My problem is, I want to run the above query for each record in :

select Telephone from PhoneDirectory

So, each telephone number in the second phone, would macth the ' ' in the first query.

How can I do so? Do I need a loop? a cursor? Can you help please?

Thanks

Sounds like you need a correlated sub-query. Seehere andhere for more help.|||

Maybe something like this?

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r ON s.Id = r.Id
INNER JOIN
PhoneDirectory pd ON pd.Telephone BETWEEN FromTelephone AND ToTelephone

|||You could prob' do it by self joining too|||

Thanks for all.

Darek, your way is the best.

How can I join on a table without specifying that a key = key ?

You just joined on a table to get the phone number from and said

"inner join ... ON telephon between"

Can you explain that to me please?

That was a great tip.

Thanks a lot.

|||

Thanks.

Everything afterON inJOIN clause is nothing more like simply conditions.

You can write something like that:

FROM a
inner join b.SomeVarChar LIKE a.SomeOtherVarChar

Previous query in ther way:

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r
INNER JOIN
PhoneDirectory pd
WHERE
s.Id = r.Id
AND pd.Telephone BETWEEN FromTelephone AND ToTelephone

Best Method to update table...

Hy everyone.
I've got a little question regarding the speed of an update query...

situation:
I've got different tables containing information wich i want to add to one big table trough a schedule (or as fast as possible).

Bigtable size:
est. 180000 records with 25 fields (most varchar).

Currently I've tried two different methods:
delete all rows in the big table and add the ones from the little tables again. (trough union all query)
-> Speed ~ 15 Seconds

refresh all changed rows (trough timestamp <>) and add new titles (trough union all query)
-> Speed ~ 20 Seconds

Does anybody know a faster solution? The union queries block the table for those 20 Seconds...

Thanks for any reply!RE: situation: I've got different tables containing information which i want to add to one big table trough a schedule (or as fast as possible).
Bigtable size:
est. 180000 records with 25 fields (most varchar).

Currently I've tried two different methods:
delete all rows in the big table and add the ones from the little tables again. (trough union all query)
-> Speed ~ 15 Seconds

refresh all changed rows (trough timestamp <>) and add new titles (trough union all query)
-> Speed ~ 20 Seconds

Q1 Does anybody know a faster solution? The union queries block the table for those 20 Seconds... Thanks for any reply!

A1 Maybe.

As with many things, it depends on the requirements. For example, some possible considerations may include various permutations and combinations of any of the following: (not an exhaustive list)
a using a lower isolation level for the union queries, and conditionally unioning only updated tables
b implementing triggers to update the target as dml is commited at the source tables
c a create, populate, and rename table scheme (dropping the old table)

Best method for query against large database(zip codes)

I am a little unsure of the best way of doing things. I am creating a dealer locator module. I have the database which contains all necessary info such as zipcode, latitude, longitude called ZipCode. I obviously have a Dealers table which has dealer info, including zipcode. My question for the community is if there is a better way to do this process, because we in the usa alone there is over 65k zipcodes, and large chains can have thousands of locations.

Currently, i grab the zipcode and the radius the want results on from a form. I then take the zipcode and query the database, returning the lat and long of the zip the user entered on the form.

I pass this lat and long to the next procedure which incorporates the radius taken in on the form. This calculates all the lats and longs i will use to "box" off my area to perform a query on areas located within the box.

I then query Zipcodes (select * zipcodes where...) using <= and >= for all sides of the "box"(high and low latitude, and high and low longitude) at this point an inner join is done by zipcode with the zipcode on the dealers table.

Lastly, I do a distance calculation on the returned data dropping all those not within the radius.

Besides anyone have a better way to do this, does anyone have a suggestion about this:
Do I use a inner join for the dealer locator, or should I just add the lat and long to the dealers table automatically upon dealer registration of a cite?


CREATE PROCEDURE dbo.sp_GetDistanceByZip
(
@.StartZip char(5),
@.EndZip char(5)
)
AS
SET NOCOUNT ON
--DECLARE @.StartZip char(5)
--DECLARE @.EndZip char(5)

--SET @.StartZip = '92833'
--SET @.EndZip = '90005'

DECLARE @.LatA float
DECLARE @.LongA float
DECLARE @.LatB float
DECLARE @.LongB float
DECLARE @.Distance float

SET @.LatA = pi() * (Select Top 1 Latitude From zips Where ZipCode = @.startZip) / 180
SET @.LongA = pi() * (Select Top 1 Longitude From zips Where ZipCode = @.startZip) / 180
SET @.LatB = pi() * (Select Top 1 Latitude From zips Where ZipCode = @.endZip) / 180
SET @.LongB = pi() * (Select Top 1 Longitude From zips Where ZipCode = @.endZip) / 180

SET @.Distance = ACOS(
SIN
(
convert(Float,(@.LatA))
)
*SIN
(
convert(Float,(@.LATB))
)
+COS
(
convert(Float,(@.LatA))
)
*COS
(
convert(Float,(@.latB))
)
*COS
(
convert(Float,((@.longa) - (@.LongB)))
)
) * 3963.1

SELECT @.Distance, @.lata, @.longa, @.latb, @.longb
GO

My suggestion for you is to use many short selects rather than a huge join. It'll run much faster, and index it properly.|||Thank you for the reply.
Question:
If I have narrowed down the amount of possible zip codes by my "box"(only the zips, lats, and longs are going to be returned that fall within this "box"), and I then do the join, is this more taxing on the system than your suggestion?|||It is less. you should try to stay away from processing in the SQL part as much as possible.

I would also have gone with a "box" solution.|||Thanks for the input.

I would strongly suggest for anyone interested in this, to purchase the solution along with a subscription for the database. For me, this is more of a matter of being able to do it rather than saving money. If it were a matter of dollars and cents, this solution would cost me roughly forty dollars for a site, and I spent an entire day on it. I may not be the best programmer, but I am worth more than 40 a day.|||Honestly, I have the entire US/Canada, and I've run that procedure with 10 threads. Each returned in less than 2 seconds. I've condensed it to specific regions and such, but for the most part, I'm very much ok with it's performance.

Explain your "boxing" method. That interests me|||Draw a cricle, now draw a box around it, the square should touch the box at four points, all other points contained within the circle are also contained within the box. Why should we query the entire continent or world if we can calculate that box from the radius using latitude and longitude. This drastically limits the number of records that we have to due our distance calculation on. We just get the zipcode and radius from the user, pull the latitude and longitude from the database by doing a select statement of the row containing that zipcode input by the user, next we do some calculations that determine our box from the radius where the centerpoint is the zipcode. Then we select only those records whose latitude and longitude fall within our box. Then we calculate distance based on only those in the box instead of the entire country, continent, etc. Everything outside of our radius distance, gets dropped(these would have still fallen within the box). The results are returned to the user.

I hope I am clear and this explains the "box" technique. Any questions, just post back. There is a little more than what I said which is involved in this, i just tried to explain it as simple as I could. Much easier to draw something like this than use words.|||Hi, I was just wondering...did you ever happen to find a fast solution to your problem?

I am currently working on a project that involved US AND Canada zip codes.

Seeing as Canada has over 700,000 post codes I really need to find the fastest way to accomplish returning results.

The way my app will need to work is pass 1 postal code...and return all records within a 50 mile radius.

Can you please let me know how your project went? Can you please share with me how you were able to achieve this?|||This really sholud not be an issue. We have databases of 300 million records that can be parsed quickly. It is down to your indexing strategies.

For retrieving areas within a circle, use a bit of pythagoras to work out the distances. Job's done pretty easy :)|||i am also about to take on this type of project with the exact same concept...I need to retrieve a business located within a 50 mile radius from a zip code. So any input on this would be great. I am assuming I need to buy a zip code database so if anyone knows of one that will accomplish this please let me know.

if anyone is interested in building it or has the code let me know what you charge to do it.
contact me at rpanek90@.hotmail.com

Saturday, February 25, 2012

Best database IDE around

Hi!
For some time I've been looking at alternative tools for query construction
that could replace the old good Query Analyzer.
I think QA is a great tool for its purpose but it has become outdated and
it's missing some of the features we have come to expect in modern IDEs, like
Intellisense support for database objects, a Visual Studio-like Server
Explorer, some kind of project management (meaning the possibility to
organize my SQL files in projects) and a good debugger for stored procedures,
among others.
I've used Visual Studio .NET for a while for debugging stored procedures and
I think it was good but what I'm looking for is a tool especially dedicated
to the purpose of building queries and (possibly) managing database objects.
I've looked at the new Management Studio for SQL Server 2005 and I think it's
the closest thing to that kind of tools but I'm also interested in free/open
source alternatives.
Does anyone know of such a tool? I'm interested in hearing about what other
database administrators/developers' favourite tools are.
Thanks in advance
/Enrico
You can have a look at foxySQL
http://www.casestudio.com/enu/databa...l_foxysql.aspx
It's free and has some features like intellisense, but to be honest
I've gone back to QA.
M
|||Enrico Campidoglio wrote:

> the closest thing to that kind of tools but I'm also interested in free/open
> source alternatives.
Visit http://www.sqlmanager.net - they offer both free and commercial
utilities for many popular RDBMS (MSSQL, IB/FB, MySQL,...)
Christmas Carol
|||If you are looking to use QA or SQL Server 2005 Management Studio, and
want to add SQL Intellisense to these tools then you might want to
check out PromptSQL: http://www.promptsql.com/
Its not free, but at US$25/user its not too expensive either. One
month evaluation download.

Sunday, February 19, 2012

Being smart or bug?(mssql2000)

Why this query works:

use northwind
select distinct em.EmployeeID
from employees as em
inner join EmployeeTerritories as et
on em.EmployeeID = et.employeeid
where e.m.country='uk'

Pay attention on the las line.
As you see it is written "e.m.country" instead of "em.country".

This is a bug in the parser for SQL Server 2000. It is present in SQL Server 2005 also but only in compatibility modes below 90. If your database is in 90 compat mode then you will get an error like:

.Net SqlClient Data Provider: Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "e.m.country" could not be bound.

The behavior is retained in older compat modes for backward compatibility reasons and to ensure that existing code works fine upon upgrade to SQL Server 2005. Hope this clarifies.

Thursday, February 16, 2012

behavior of command in the 'SQL Query Analyzer'

Hello,
A command in 'SQL Query Analyzer does not return expected results.
This command:
sp_depends 'lkpRate'
Returns these results:
dbo.usp_Rate_delstored procedure
dbo.usp_Rate_insstored procedure
dbo.usp_Rate_updstored procedure
But fails to return:
dbo.usp_Rate_sel
This command:
sp_depends 'usp_rate_sel'
Returns this result:
Object does not reference any object, and no objects reference it.
Here is the table 'lkpRate':
\\CREATE TABLE [lkpRate] (
[pkRateId] [smallint] IDENTITY (1, 1) NOT NULL ,
[fkRateTypeId] [smallint] NOT NULL ,
[RateDescription] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[Switch1] [tinyint] NOT NULL CONSTRAINT [DF_lkpRate_switch1] DEFAULT
(0),
[Rate] [smallmoney] NOT NULL ,
[rOrd] [tinyint] NOT NULL CONSTRAINT [DF_tblStartupAsst_saOrd] DEFAULT
(0),
[rHide] [bit] NOT NULL CONSTRAINT [DF_tblStartupAsst_saHide] DEFAULT
(0),
CONSTRAINT [PK_tblStartupAsst] PRIMARY KEY CLUSTERED
(
[pkRateId]
) WITH FILLFACTOR = 90 ON [PRIMARY] ,
CONSTRAINT [FK_lkpRate_lkpRateType] FOREIGN KEY
(
[fkRateTypeId]
) REFERENCES [lkpRateType] (
[pkRateTypeId]
) NOT FOR REPLICATION
) ON [PRIMARY]
GO
//
Here is the stored procedure:
\\
CREATE PROCEDURE dbo.usp_Rate_sel
AS
SET NOCOUNT ON;
SELECT
pkRateId,
fkRateTypeId,
RateDescription,
Switch1,
Rate,
rOrd,
rHide
FROM dbo.lkpRate
GO
//
What do you make of it that Query Analyzer doesn't see the stored
procedure as belonging to the table?
Thank you,
dbuchanan
Dependency information is maintained correctly only when objects are
(re)created in correct dependency order. If usp_rate_sel was created before
the table or if the table was later recreated, dependency info will be
incomplete. You can fix correct the dependency information by recreating
usp_rate_sel.
Hope this helps.
Dan Guzman
SQL Server MVP
"dbuchanan" <dbuchanan52@.hotmail.com> wrote in message
news:1141047719.180447.206490@.i40g2000cwc.googlegr oups.com...
> Hello,
> A command in 'SQL Query Analyzer does not return expected results.
> This command:
> sp_depends 'lkpRate'
> Returns these results:
> dbo.usp_Rate_del stored procedure
> dbo.usp_Rate_ins stored procedure
> dbo.usp_Rate_upd stored procedure
> But fails to return:
> dbo.usp_Rate_sel
> This command:
> sp_depends 'usp_rate_sel'
> Returns this result:
> Object does not reference any object, and no objects reference it.
> Here is the table 'lkpRate':
> \\CREATE TABLE [lkpRate] (
> [pkRateId] [smallint] IDENTITY (1, 1) NOT NULL ,
> [fkRateTypeId] [smallint] NOT NULL ,
> [RateDescription] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [Switch1] [tinyint] NOT NULL CONSTRAINT [DF_lkpRate_switch1] DEFAULT
> (0),
> [Rate] [smallmoney] NOT NULL ,
> [rOrd] [tinyint] NOT NULL CONSTRAINT [DF_tblStartupAsst_saOrd] DEFAULT
> (0),
> [rHide] [bit] NOT NULL CONSTRAINT [DF_tblStartupAsst_saHide] DEFAULT
> (0),
> CONSTRAINT [PK_tblStartupAsst] PRIMARY KEY CLUSTERED
> (
> [pkRateId]
> ) WITH FILLFACTOR = 90 ON [PRIMARY] ,
> CONSTRAINT [FK_lkpRate_lkpRateType] FOREIGN KEY
> (
> [fkRateTypeId]
> ) REFERENCES [lkpRateType] (
> [pkRateTypeId]
> ) NOT FOR REPLICATION
> ) ON [PRIMARY]
> GO
> //
> Here is the stored procedure:
> \\
> CREATE PROCEDURE dbo.usp_Rate_sel
> AS
> SET NOCOUNT ON;
> SELECT
> pkRateId,
> fkRateTypeId,
> RateDescription,
> Switch1,
> Rate,
> rOrd,
> rHide
> FROM dbo.lkpRate
> GO
> //
> What do you make of it that Query Analyzer doesn't see the stored
> procedure as belonging to the table?
> Thank you,
> dbuchanan
>
|||Dan
Thank you.
Is there any way, maybe some command that I can use, to identify those
objects that are not up to date?
'sp_depends' seems kind of worthless if information must be accounted
for 'manually' in order for the commands to work.
dbuchanan
|||dbuchanan (dbuchanan52@.hotmail.com) writes:
> Is there any way, maybe some command that I can use, to identify those
> objects that are not up to date?
Not really. You could run a SELECT on sysobjects to identify procedures
that have been created before tables, but that will probably give you
too much information.

> 'sp_depends' seems kind of worthless if information must be accounted
> for 'manually' in order for the commands to work.
Yes, it is a feature or limited use. I use it quite a bit myself though,
but what I do is that I build an empty database with our build tools, so
that I know that dependencies from tables to procedures are correct.
(Dependencies from procedures are not.)
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

behavior of command in the 'SQL Query Analyzer'

Hello,
A command in 'SQL Query Analyzer does not return expected results.
This command:
sp_depends 'lkpRate'
Returns these results:
dbo.usp_Rate_del stored procedure
dbo.usp_Rate_ins stored procedure
dbo.usp_Rate_upd stored procedure
But fails to return:
dbo.usp_Rate_sel
This command:
sp_depends 'usp_rate_sel'
Returns this result:
Object does not reference any object, and no objects reference it.
Here is the table 'lkpRate':
\\CREATE TABLE [lkpRate] (
[pkRateId] [smallint] IDENTITY (1, 1) NOT NULL ,
[fkRateTypeId] [smallint] NOT NULL ,
[RateDescription] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[Switch1] [tinyint] NOT NULL CONSTRAINT [DF_lkpRate_switch1] DEFAULT
(0),
[Rate] [smallmoney] NOT NULL ,
[rOrd] [tinyint] NOT NULL CONSTRAINT [DF_tblStartupAsst_saOrd] DEFAULT
(0),
[rHide] [bit] NOT NULL CONSTRAINT [DF_tblStartupAsst_saHide] DEFAULT
(0),
CONSTRAINT [PK_tblStartupAsst] PRIMARY KEY CLUSTERED
(
[pkRateId]
) WITH FILLFACTOR = 90 ON [PRIMARY] ,
CONSTRAINT [FK_lkpRate_lkpRateType] FOREIGN KEY
(
[fkRateTypeId]
) REFERENCES [lkpRateType] (
[pkRateTypeId]
) NOT FOR REPLICATION
) ON [PRIMARY]
GO
//
Here is the stored procedure:
\\
CREATE PROCEDURE dbo.usp_Rate_sel
AS
SET NOCOUNT ON;
SELECT
pkRateId,
fkRateTypeId,
RateDescription,
Switch1,
Rate,
rOrd,
rHide
FROM dbo.lkpRate
GO
//
What do you make of it that Query Analyzer doesn't see the stored
procedure as belonging to the table?
Thank you,
dbuchananDependency information is maintained correctly only when objects are
(re)created in correct dependency order. If usp_rate_sel was created before
the table or if the table was later recreated, dependency info will be
incomplete. You can fix correct the dependency information by recreating
usp_rate_sel.
Hope this helps.
Dan Guzman
SQL Server MVP
"dbuchanan" <dbuchanan52@.hotmail.com> wrote in message
news:1141047719.180447.206490@.i40g2000cwc.googlegroups.com...
> Hello,
> A command in 'SQL Query Analyzer does not return expected results.
> This command:
> sp_depends 'lkpRate'
> Returns these results:
> dbo.usp_Rate_del stored procedure
> dbo.usp_Rate_ins stored procedure
> dbo.usp_Rate_upd stored procedure
> But fails to return:
> dbo.usp_Rate_sel
> This command:
> sp_depends 'usp_rate_sel'
> Returns this result:
> Object does not reference any object, and no objects reference it.
> Here is the table 'lkpRate':
> \\CREATE TABLE [lkpRate] (
> [pkRateId] [smallint] IDENTITY (1, 1) NOT NULL ,
> [fkRateTypeId] [smallint] NOT NULL ,
> [RateDescription] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [Switch1] [tinyint] NOT NULL CONSTRAINT [DF_lkpRate_switch1] DEFAULT
> (0),
> [Rate] [smallmoney] NOT NULL ,
> [rOrd] [tinyint] NOT NULL CONSTRAINT [DF_tblStartupAsst_saOrd] DEFAULT
> (0),
> [rHide] [bit] NOT NULL CONSTRAINT [DF_tblStartupAsst_saHide] DEFAULT
> (0),
> CONSTRAINT [PK_tblStartupAsst] PRIMARY KEY CLUSTERED
> (
> [pkRateId]
> ) WITH FILLFACTOR = 90 ON [PRIMARY] ,
> CONSTRAINT [FK_lkpRate_lkpRateType] FOREIGN KEY
> (
> [fkRateTypeId]
> ) REFERENCES [lkpRateType] (
> [pkRateTypeId]
> ) NOT FOR REPLICATION
> ) ON [PRIMARY]
> GO
> //
> Here is the stored procedure:
> \\
> CREATE PROCEDURE dbo.usp_Rate_sel
> AS
> SET NOCOUNT ON;
> SELECT
> pkRateId,
> fkRateTypeId,
> RateDescription,
> Switch1,
> Rate,
> rOrd,
> rHide
> FROM dbo.lkpRate
> GO
> //
> What do you make of it that Query Analyzer doesn't see the stored
> procedure as belonging to the table?
> Thank you,
> dbuchanan
>|||Dan
Thank you.
Is there any way, maybe some command that I can use, to identify those
objects that are not up to date?
'sp_depends' seems kind of worthless if information must be accounted
for 'manually' in order for the commands to work.
dbuchanan|||dbuchanan (dbuchanan52@.hotmail.com) writes:
> Is there any way, maybe some command that I can use, to identify those
> objects that are not up to date?
Not really. You could run a SELECT on sysobjects to identify procedures
that have been created before tables, but that will probably give you
too much information.

> 'sp_depends' seems kind of worthless if information must be accounted
> for 'manually' in order for the commands to work.
Yes, it is a feature or limited use. I use it quite a bit myself though,
but what I do is that I build an empty database with our build tools, so
that I know that dependencies from tables to procedures are correct.
(Dependencies from procedures are not.)
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Start by generating a script file in Enterprise Manager. Include all
stored procedures and views. Script as CREATE, but do NOT include the
DELETE!
Now edit the script, and change all the CREATE PROC and CREATE VIEW to
ALTER commands.
Then run the script. Run it a few times, if you want. I believe the
dependencies should be up to date.
(Personally I don't pay any attention to those dependencies, but that
is partly because I formed my habits before they introduced ALTER!)
Roy
On 27 Feb 2006 07:22:50 -0800, "dbuchanan" <dbuchanan52@.hotmail.com>
wrote:

>Dan
>Thank you.
>Is there any way, maybe some command that I can use, to identify those
>objects that are not up to date?
>'sp_depends' seems kind of worthless if information must be accounted
>for 'manually' in order for the commands to work.
>dbuchanan

Beginning Balance Query

Hello all,
I would like a total (beginning balance) field in a query be the total for
the year up to the month based on another field within the query, so that
when the fiscal_date = '5/1/2006' that I would have a field contain totals
from '1/1/2006' thru '4/30/2006'. I would like to do this in one query, I am
trying to populate a table with 6 years of data that would have a beginning
balance field and then todays current amount based off of a Fiscal_Date fiel
d.
My problem is I cannot figure out how to do a sum of prior data based off of
another fields current date. Am I trying to do too much in one query to
populate the table?Lyners wrote:
> Hello all,
> I would like a total (beginning balance) field in a query be the total for
> the year up to the month based on another field within the query, so that
> when the fiscal_date = '5/1/2006' that I would have a field contain totals
> from '1/1/2006' thru '4/30/2006'. I would like to do this in one query, I
am
> trying to populate a table with 6 years of data that would have a beginnin
g
> balance field and then todays current amount based off of a Fiscal_Date fi
eld.
> My problem is I cannot figure out how to do a sum of prior data based off
of
> another fields current date. Am I trying to do too much in one query to
> populate the table?
>
Without DDL, I don't know your actual table/field names, but something
like this should be close:
SELECT
Table2.FiscalDate,
(SELECT SUM(Amount) FROM Table1 WHERE DATEPART(year, DateField) =
DATEPART(year, Table2.FiscalDate) AND DATEPART(month, DateField) <
DATEPART(month, Table2.FiscalDate)) AS FiscalAmount
FROM Table2|||Thank you Tracy,
Yes, I did something close to this. What I ended up doing was create 2
tablkes that were identical, and then used a cross join where one of my
criteria is that a.date < b.date, then in the select statement I added a
sum(a.amount). This way I sum all a.amount that is less than b.date.
This way I have all of the b table fields and the total of the amount from
the a table all together.
Thank you,
Lyners
"Tracy McKibben" wrote:

> Lyners wrote:
> Without DDL, I don't know your actual table/field names, but something
> like this should be close:
> SELECT
> Table2.FiscalDate,
> (SELECT SUM(Amount) FROM Table1 WHERE DATEPART(year, DateField) =
> DATEPART(year, Table2.FiscalDate) AND DATEPART(month, DateField) <
> DATEPART(month, Table2.FiscalDate)) AS FiscalAmount
> FROM Table2
>|||Why would you create a second identical table when a VIEW would most likely
have worked -without the issues of keeping 2 tables syncronized?
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"Lyners" <Lyners@.discussions.microsoft.com> wrote in message
news:7FA08953-C425-43CD-A198-3CBC08EA229E@.microsoft.com...
> Thank you Tracy,
> Yes, I did something close to this. What I ended up doing was create 2
> tablkes that were identical, and then used a cross join where one of my
> criteria is that a.date < b.date, then in the select statement I added a
> sum(a.amount). This way I sum all a.amount that is less than b.date.
> This way I have all of the b table fields and the total of the amount from
> the a table all together.
> Thank you,
> Lyners
> "Tracy McKibben" wrote:
>|||Good point Arnie. I actually just created a large query that has 2 identical
select statements. The second select statement I total the amount field base
d
on the cross join where clause. I am in the design phase of this report, so
in the future, I will most likely create a view (faster) of the select query
and just reference that instead of requerying everytime.
Thanks for the performance pointer.
"Arnie Rowland" wrote:

> Why would you create a second identical table when a VIEW would most likel
y
> have worked -without the issues of keeping 2 tables syncronized?
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another certification Exam
>
> "Lyners" <Lyners@.discussions.microsoft.com> wrote in message
> news:7FA08953-C425-43CD-A198-3CBC08EA229E@.microsoft.com...
>
>

Monday, February 13, 2012

Beginners SQL Query i cant suse out

HI,
I have what should be a simple query , but I just dont seem to have the head
for it :
Tables :
Tables
TableID
TableName
OpenedTime
Covers
CoverID
CoverNumber
TableID_FK
The query is to return back the number of times the table was opened in a
given period and how many covers there were also for this given period. What
I have so far that is wrong :
SELECT COUNT(Tables.TableID), COUNT(Covers.CoverNumber)
FROM Table_Archive INNER JOIN
Covers_Archive ON Table_Archive.TableArchiveID =
Covers_Archive.TableArchiveID_FK
ThanksI think I sorted using "DISTINCT"
"Jon Vaughan" <jonnyvaughan@.hotmail.com> wrote in message
news:urHPf.24197$Gh4.17452@.fe07.news.easynews.com...
> HI,
> I have what should be a simple query , but I just dont seem to have the
> head for it :
> Tables :
> Tables
> TableID
> TableName
> OpenedTime
> Covers
> CoverID
> CoverNumber
> TableID_FK
> The query is to return back the number of times the table was opened in a
> given period and how many covers there were also for this given period.
> What I have so far that is wrong :
> SELECT COUNT(Tables.TableID), COUNT(Covers.CoverNumber)
> FROM Table_Archive INNER JOIN
> Covers_Archive ON Table_Archive.TableArchiveID =
> Covers_Archive.TableArchiveID_FK
>
> Thanks
>|||I'm not at all sure I understand what you are asking for, but try
changing the COUNTs to COUNT(distinct):
COUNT(distinct Tables.TableID)
COUNT(distinct Covers.CoverNumber)
Roy Harvey
Beacon Falls, CT
On Wed, 08 Mar 2006 20:49:31 GMT, "Jon Vaughan"
<jonnyvaughan@.hotmail.com> wrote:

>HI,
>I have what should be a simple query , but I just dont seem to have the hea
d
>for it :
>Tables :
>Tables
>TableID
>TableName
>OpenedTime
>Covers
>CoverID
>CoverNumber
>TableID_FK
>The query is to return back the number of times the table was opened in a
>given period and how many covers there were also for this given period. Wha
t
>I have so far that is wrong :
>SELECT COUNT(Tables.TableID), COUNT(Covers.CoverNumber)
>FROM Table_Archive INNER JOIN
> Covers_Archive ON Table_Archive.TableArchiveID =
>Covers_Archive.TableArchiveID_FK
>
>Thanks
>|||First of all, your table name in your list don't appear to match what's
in the SQL code. So I made some Create Table/Insert statements to have
something to work with. Plus, you never explained what data types the
columns are supposed to be. So I made it up. :) Those are:
Create Table Table_Archive (TableID int, TableName nvarchar(20),
OpenedTime DateTime)
Create Table Covers_Archive (CoverID int, CoverNumber int, TableID_FK
int)
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (1,
'Test1', '3/8/06 1 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (1,
'Test1', '3/8/06 3 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (1,
'Test1', '3/8/06 7 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (1,
'Test1', '3/9/06 1 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (2,
'Test2', '3/8/06 1 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (2,
'Test2', '3/8/06 3 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (2,
'Test2', '3/8/06 7 pm')
Insert Into Table_Archive (TableID,TableName,OpenedTime) Values (2,
'Test2', '3/9/06 1 pm')
Insert Into Covers_Archive (CoverID,CoverNumber,TableID_FK) Values
(1,99,1)
Insert Into Covers_Archive (CoverID,CoverNumber,TableID_FK) Values
(2,99,1)
Insert Into Covers_Archive (CoverID,CoverNumber,TableID_FK) Values
(3,67,2)
Insert Into Covers_Archive (CoverID,CoverNumber,TableID_FK) Values
(4,88,2)
Using the above, the SQL below should give you what I t hink you are
looking for.
SELECT T.TableName,
T.OpenCount,
C.CoverCount
FROM
(SELECT TableName,
TableID,
COUNT(TableID) OpenCount
FROM Table_Archive
GROUP BYTableName,TableID) T
JOIN
(SELECT TableID_FK,
Count(DISTINCT CoverNumber) CoverCount
FROM Covers_Archive
GROUP BY TableID_FK) C
ON T.TableID = C. TableID_FK

BEGINNER'S QUESTION: SORTING IN ALPHABETICAL ORDER

Hi

I am trying to convert an Access back end into a SQL Server back end and cannot work out how to convert a query that sorts addresses that start with numbers into alphabetical order.

In Access I defined a function that converted the full address to one without the initial numbers eg:
66 Acacia Gardens to Acacia Gardens

I then used this function as an expression in the field column of the query and set it to sort by this field. This put the rows into alphabetical order. (A second function was used to return just the number which was used as the second sort).

I am converting the Access query into a stored procedure. I have successfully converted the Access number removal function into a separate stored procedure and I was intending to execute it from within the main stored procedure but I cannot work out how to do this. I don't think you can insert an Execute statement into a field as you can with a function in Access.

Code for working number removal stored procedure:

ALTER PROCEDURE spRemoveInitialNumbers
@.JobName varchar(20), @.FirstNumbersRemoved varchar(20) OUTPUT
As
DECLARE @.Chopped varchar(20)
DECLARE @.CharacterCount tinyint
DECLARE @.CharacterCode tinyint
SET @.Chopped = @.JobName
IF Substring(@.Chopped,1,5) = 'Unit '
Begin
SET @.Chopped = Right(@.Chopped, Len(@.Chopped)-5)
End
ELSE
SET @.CharacterCount = 1
WHILE @.CharacterCount<=Len(@.Chopped)
BEGIN
SET @.CharacterCode=Ascii(Substring(@.Chopped,@.CharacterCount,1))
If @.CharacterCode>64 and @.CharacterCode<91
Begin
SET @.Chopped=Right(@.Chopped, Len(@.Chopped) - @.CharacterCount + 1)
Break
End
Else
Set @.CharacterCount = @.CharacterCount + 1
End
SET @.FirstNumbersRemoved=@.Chopped

Code for non-working main stored procedure:

SELECT dbo.tblJobs.JobID, dbo.tblJobs.JobNumber, dbo.tblJobs.Surveyor, dbo.tblClients.ClientName, dbo.tblJobs.JobName, dbo.tblJobs.Description,
dbo.tblJobs.Status, dbo.tblJobs.UrgencyCode, dbo.tblJobs.EstimatedFeesOutstanding, dbo.tblJobs.[Live/Dead],
[Intended to Execute SpRemoveInitialNumbers here] AS Expr1,
SUM(dbo.tblFeeAccounts.TotalLessVATandExpenses - dbo.tblFeeAccounts.SubContactors) AS TotalNet, dbo.tblJobs.InstructionDate
FROM dbo.tblJobs INNER JOIN
dbo.tblClients ON dbo.tblJobs.ClientID = dbo.tblClients.ClientID LEFT OUTER JOIN
dbo.tblFeeAccounts ON dbo.tblJobs.JobID = dbo.tblFeeAccounts.JobID
GROUP BY dbo.tblJobs.JobNumber, dbo.tblJobs.Surveyor, dbo.tblClients.ClientName, dbo.tblJobs.JobName, dbo.tblJobs.Description, dbo.tblJobs.Status,
dbo.tblJobs.UrgencyCode, dbo.tblJobs.EstimatedFeesOutstanding, dbo.tblJobs.[Live/Dead], dbo.tblJobs.InstructionDate, dbo.tblJobs.JobID
HAVING (dbo.tblJobs.[Live/Dead] = N'D')
ORDER BY dbo.tblClients.ClientName, dbo.tblJobs.JobName

I would like to undertake the sort on the server, not client side hence my attempt to use stored procedures. I'm not sure that I am going about this the right way. Can anyone help me?

Many thanks.

Whitebeam

Please put the logic of SpRemoveInitialNumbers SP into a TSQL scalar user-defined function. You can then call it from the SELECT list. Alternatively, you can also embed the required substring / charindex / patindex expression in the SELECT list itself for better performance. ( I am assuming you use such functions to remove the initial numbers).

Beginners Question: How to write this query

Hi -

I feel stupied b/c I can't figure this out but I hope it's just a few seconds for some of the more senior posters of this forum:

I have a table that looks like this:

Table:Request
ID: bigint
... (a bunch of table specific columns)
User_Status_ID: bigint (holds the bigint ID of the status table, below; always holds the ID to the most recent ID, if several)
Provider_Status_ID: bigint (holds the bigint ID of the status table, below; always holds the ID to the most recent ID, if several)

and then there is a second table that looks like this:

Table: Status
ID: bigint
RequestID: bigint (the request ID, so I can see all status messages for the request)
Time: Timestamp
Code: byte (there are only a few status messages)

The status table holds both the status for users and providers, as they use exactly the same status code. What I'd like to get is a table/view that looks like this:

RequestID:bigint (the request that this status belongs to)
User_Code: byte (the code of th most recent user status)
Provider_Code: byte (the code of the most recent provider status)

Somehow, I am blanking how to create a query that returns both user and provider codes in one row. Any help greatly appreciated!!!!

Oliver

Why has the Status table the column RequestID?

Otherwise the SELECT you want is along the lines of

SELECT RequestID, U.Code, P.Code FROM Request, Status U, Status P WHERE Request.User_Status_Id = U.Id AND Request.Provider_Code = P.Id

|||

Thanks - that improves my life. I had used multiple views before and it was getting messy ...