Showing posts with label least. Show all posts
Showing posts with label least. Show all posts

Tuesday, March 20, 2012

comprehensive details for setting up SSE?

First, soapbox questions for someone who might have more direct pull with Microsoft (or at least knowledge of how I should work with what they've given us), then a more specific question:

Scenario: You install SQL Server Express (or any other version, it doesn't matter) and the feedback with all the little green checkmarks tells you it has installed successfully. "Oh goody," say people (like me) who are not super experienced with SQL Server, "it installed successfully; now I can jump in and start using it!" But it aint so--there are so many other hoops to jump through before it really becomes operational.

After successful installation, why can't some link become visible indicating what you have to do after that? I mean, it's fine to wade through all the questions in this forum and get answers from all you nice and informed guys, AFTER the problems start coming; but I would rather not have to associate with you, to be honest, in terms of time spent that could be going into my projects.

Why isn't there a comprehensive guide right off the bat? That is, something referenced immediately that tells you such things as: how to register a database with emphasis on the fact that just creating a database won't do the trick for your application; how to set permissions and rights; that (what was I reading in the advice of one post?) you have to register both the database and the user, blah blah; all about instances, the web.config file, etc. etc. I mean, doesn't it seem logical that by virtue of a person installing the database, come on, that this is a pretty good indication that he/she in all likelihood is new at it? As it is now, all they tell you on the SSE site is that you have to have the .NET Framework installed; and the green checkmarks indicating that you've installed it correctly (sorry for mentioning that twice).

"OK, self," I say, "I have the Framework installed and SSE installed correctly, so let's get to work." Then the trouble begins. Unless Microsoft's purpose is to keep you tech guys and book writers in business, I don't understand why they don't give more up-front guidance. Any thoughts on why they work it this way? Bueller, Bueller? Anyone, anyone?

Now, to the question that's pressing me at the moment: I've installed SSE and I'm going through a tutorial ("How Do I: Create Data-Driven Web Sites?" onhttp://www.asp.net/getstarted/default.aspx?tabid=61). Yeah, the guy makes it look really easy. He creates a database then shuts down the connection. I try to do the same things and I'm informed that I don't even have a valid connection! How SQL-Server-Express fun and easy is that? It's a real AdventureWorks, if you ask me.

OK, that's my rant; and since MS didn't think in advance and implement my idea of a link to jump off from the installation menu, I have to face the reality of learning this by putting all the pieces together myself. So, my question is, before I try to go through the video and get more frustrated, WHERE DO I GO FOR THE MOST BASIC OF ALL THE STEPS I NEED TO DO, ONE BY ONE? This is like the second "beginner" video I've tried to go through but even these don't start at the very beginning with information on how to register a new database, making the user a part of aspnetWHATEVER, what permissions to dole out, etc.

Guidance is solicited and will be most appreciated. Thanks, Bryan

Hi,

I saw this: Http:www.sswug.org/see/21350 I haven't done the registration to access this site, so I can't say it will help. (Just came across it in a search). If you do check it out, let me know if it seems worthwhile.

BTW, I could find no Microsoft webcast/vids on installing SSE. Being a free product, the support is very limited. It's also a very complex and powerful program, and maybe it should be more surprising that the install is easy for anyone! I never seem to have the 'Standard' or 'Typical' system configuration that would make for an easy install. As i recall, the install of SQL Server 2005 (Standard) went easier for me than the SSE install.

I did install SSE for use with developing ASP.Net apps - works better with the defaults, and doesn't pose risks to the full version install. BRN..

Sunday, March 11, 2012

complicated sql query

Hello all,
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName =
[Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose
Patrice
On Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:

>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis

complicated sql query

Hello all,
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName =
[Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose
PatriceOn Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:

>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis

complicated sql query

Hello all,
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName = [Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose :)
PatriceOn Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:
>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose :)
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis

Complicated join query - how is this done?

At least this is complicated for me. I hope it's not trivial for you
experts!
Accounts table has Acct_Number (unique), Client_ID, and Rep_Num. The
rep num is the number that identifies the registered representative(s)
on the account. (The client ID, of course, points to the client's name,
address, and other stuff in another table.)
The Rep_Nums table has Rep_Num (not unique) and Rep_ID. Each rep number
can map to many rep IDs. Many acccounts are assigned to a "split rep"
number where two (or more) individual "rep persons" share the work of
servicing the account and share the commissions.
The Rep_Names table has Rep_ID (unique), Rep_FName, and Rep_LName with
the rep-person's first and last name.
So far, straightforward.
Now, when we display account information, we usually don't need to see
the names of all reps assigned to the rep number on the account -- any
one rep-person's first and last name is enough information for internal
display purposes (in case we need to call one of the reps on an account
for some reason).
Now I figured out one way to do this -- I created a Rep_View that groups
the rep_nums table by rep number, and picks the smallest rep_id for each
one, and returns that rep's first and last name.
So when I want to display account information along with the name of one
of the reps on the account, I use the rep view instead of the underlying
tables.
But::: The rep name information comes from external data sources that
we have no control over, and the rep's first and last names are null for
many of the rep_IDs in the rep_names table. We're trying to fill in the
missing information, but it's a slow process, and in the meantime, we
need to show reports.
Of course, sometimes a rep number points to two rep IDs, and one of
those rep IDs has a first and last name in the table and the other does
not.
You might see where this is leading -- I need to display account
numbers, client IDs (I'll get the client names from another table), rep
number, and ONE of the first name/last name pairs from the rep names
table, picking any rep first name/last name pair that's not null for the
rep number.
How is this done? The only way I can think of involves creating an on-
the-fly computed column that holds rep first name concatenated with rep
last name, and pick the min or the max of that (for each rep number) to
try to get a non-null rep name pair. Then I might want to un-
concatenate that rep's name to get back to separate rep first and last
name, and that's messy.
And I don't like creating on-the-fly computed columns that concatenate
varchar fields.
Of course, all sets of rep first name/rep last names for any rep number
might be null too, and if so, we need to show null or "Unknown" for the
rep's name.
Comments are appreciated!
David WalkerSelect Acct_Number, Client_ID,
Min(Rep_FName + ' ' + Rep_LName) RepName
From Accounts A
Left Join (Rep_Nums N Join Rep_Names R
On R.Rep_ID = N.Rep_ID)
On N.Rep_Num = A.Rep_Num
And R.Rep_FName Is Not Null
And R.Rep_LName Is Not Null
"DWalker" wrote:

> At least this is complicated for me. I hope it's not trivial for you
> experts!
> Accounts table has Acct_Number (unique), Client_ID, and Rep_Num. The
> rep num is the number that identifies the registered representative(s)
> on the account. (The client ID, of course, points to the client's name,
> address, and other stuff in another table.)
> The Rep_Nums table has Rep_Num (not unique) and Rep_ID. Each rep number
> can map to many rep IDs. Many acccounts are assigned to a "split rep"
> number where two (or more) individual "rep persons" share the work of
> servicing the account and share the commissions.
> The Rep_Names table has Rep_ID (unique), Rep_FName, and Rep_LName with
> the rep-person's first and last name.
> So far, straightforward.
> Now, when we display account information, we usually don't need to see
> the names of all reps assigned to the rep number on the account -- any
> one rep-person's first and last name is enough information for internal
> display purposes (in case we need to call one of the reps on an account
> for some reason).
> Now I figured out one way to do this -- I created a Rep_View that groups
> the rep_nums table by rep number, and picks the smallest rep_id for each
> one, and returns that rep's first and last name.
> So when I want to display account information along with the name of one
> of the reps on the account, I use the rep view instead of the underlying
> tables.
> But::: The rep name information comes from external data sources that
> we have no control over, and the rep's first and last names are null for
> many of the rep_IDs in the rep_names table. We're trying to fill in the
> missing information, but it's a slow process, and in the meantime, we
> need to show reports.
> Of course, sometimes a rep number points to two rep IDs, and one of
> those rep IDs has a first and last name in the table and the other does
> not.
> You might see where this is leading -- I need to display account
> numbers, client IDs (I'll get the client names from another table), rep
> number, and ONE of the first name/last name pairs from the rep names
> table, picking any rep first name/last name pair that's not null for the
> rep number.
> How is this done? The only way I can think of involves creating an on-
> the-fly computed column that holds rep first name concatenated with rep
> last name, and pick the min or the max of that (for each rep number) to
> try to get a non-null rep name pair. Then I might want to un-
> concatenate that rep's name to get back to separate rep first and last
> name, and that's messy.
> And I don't like creating on-the-fly computed columns that concatenate
> varchar fields.
> Of course, all sets of rep first name/rep last names for any rep number
> might be null too, and if so, we need to show null or "Unknown" for the
> rep's name.
> Comments are appreciated!
>
> David Walker
>|||David,
You have posted here several times, right? How about following
www.aspfaq.com/5006?
Anith|||"examnotes" <cbretana@.areteIndNOSPAM.com> wrote in
news:D58B52E9-D083-4510-86CF-986F3981F7B5@.microsoft.com:

> Select Acct_Number, Client_ID,
> Min(Rep_FName + ' ' + Rep_LName) RepName
> From Accounts A
> Left Join (Rep_Nums N Join Rep_Names R
> On R.Rep_ID = N.Rep_ID)
> On N.Rep_Num = A.Rep_Num
> And R.Rep_FName Is Not Null
> And R.Rep_LName Is Not Null
>
That helps, thanks. I still need to get the rep names out in separate
First and Last name fields; I can put a delimiter other than space in
there and split them again, I suppose.
Thanks.
David Walker
> "DWalker" wrote:
>|||"Anith Sen" <anith@.bizdatasolutions.com> wrote in news:OT91gVpJFHA.2980
@.TK2MSFTNGP10.phx.gbl:

> David,
> You have posted here several times, right? How about following
> www.aspfaq.com/5006?
>
Sorry, I meant to add the DDL at the bottom, but I simplified some of the
fields (there are lots of fields that don't contribute to the problem) and
I was looking for techniques. I'll post the DDL next time.
David Walker|||"examnotes" <cbretana@.areteIndNOSPAM.com> wrote in
news:D58B52E9-D083-4510-86CF-986F3981F7B5@.microsoft.com:

> Select Acct_Number, Client_ID,
> Min(Rep_FName + ' ' + Rep_LName) RepName
> From Accounts A
> Left Join (Rep_Nums N Join Rep_Names R
> On R.Rep_ID = N.Rep_ID)
> On N.Rep_Num = A.Rep_Num
> And R.Rep_FName Is Not Null
> And R.Rep_LName Is Not Null
That doesn't work.
Column 'Accounts.ACCT_NUMBER' is invalid in the select list because it is
not contained in an aggregate function and there is no GROUP BY clause.
And the same message for Client_ID.
I see that you're trying to pick one of the advisor names where they are
not null, but without grouping, it doesn't work.
David|||On Fri, 18 Mar 2005 09:41:32 -0800, DWalker wrote:

>"examnotes" <cbretana@.areteIndNOSPAM.com> wrote in
>news:D58B52E9-D083-4510-86CF-986F3981F7B5@.microsoft.com:
>
>That doesn't work.
>Column 'Accounts.ACCT_NUMBER' is invalid in the select list because it is
>not contained in an aggregate function and there is no GROUP BY clause.
>And the same message for Client_ID.
>I see that you're trying to pick one of the advisor names where they are
>not null, but without grouping, it doesn't work.
>David
Hi David,
I think CBretana intended to add
GROUP BY Acct_Number, Client_ID
at the end of the query.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thanks, Hugo.
David
Hugo Kornelis <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in
news:87cm31dchmap2uano4sab114ba0fu36thq@.
4ax.com:

> On Fri, 18 Mar 2005 09:41:32 -0800, DWalker wrote:
>
> Hi David,
> I think CBretana intended to add
> GROUP BY Acct_Number, Client_ID
> at the end of the query.
> Best, Hugo

Thursday, March 8, 2012

Complicated (at least to me) insert

The best way to explain this is by example.

I have a source table with many columns.

Source
SYMBOL
EXCHANGE_NAME
CUSIP
TYPE
ISSUE_NAME
and so on

Then I have 3 other destination tables.

Exchanges
EXCHANGE_ID IDENTITY
EXCHANGE_NAME UNIQUE

SecurityMaster
SECURITY_MASTER_ID IDENTITY
SYMBOL UNIQUE
CUSIP
TYPE
ISSUE_NAME
and so on

Exchange_mm_SecurityMaster
EXCHANGE_ID
SECURITY_MASTER_ID

-- The Source table has multiple rows of the same symbol.
-- The Exchanges table is already populated with all the exchanges.
-- A single security (in the SecurityMaster table) can belong to many
Exchanges, hence the Exchange_mm_SecurityMaster table.

Now. If I just wanted to insert into the SecurityMaster table without
touching the Exchange_mm_SecurityMaster table I could just execute:

INSERT INTO SecurityMaster ([SYMBOL], [CUSIP], [TYPE], [ISSUE_NAME])
SELECT DISTINCT[SYMBOL], [CUSIP], [TYPE], [ISSUE_NAME]
FROM Source
WHERE NOT EXISTS (SELECT * FROM SecurityMaster SM WHERE SM.SYMBOL =
Source.SYMBOL)

Now to the Exchange_mm_SecurityMaster. I need the individual identity
values for each row inserted into SecurityMaster so I can then turn
around and insert into Exchange_mm_SecurityMaster. Here are the
issues/possibilities as I see it.

- @.@.IDENTITY will not work since I am not inserting a single row at a
time

- I guess I could INSERT INTO SecurityMaster first, THEN do another
INSERT INTO Exchange_mm_SecurityMaster with different where clause.

- I could create a stored procedure that does a single insert into
SecurityMaster and Exchange_mm_SecurityMaster. Then call that
procedure for each row in the SELECT DISTRICT from the Source table.
My main worry is the number of arguments passed in. My example only
shows a few but a regular SecurityMster table could have 30-50
columns.

- Maybe do something with a trigger but I am not sure if I can pass
the EXCHANGE_NAME value to the SecurityMaster trigger when that table
does not need it.

Hope I explained it clearly. Any help would be appreciated.Jason (JayCallas@.hotmail.com) writes:
> Now to the Exchange_mm_SecurityMaster. I need the individual identity
> values for each row inserted into SecurityMaster so I can then turn
> around and insert into Exchange_mm_SecurityMaster. Here are the
> issues/possibilities as I see it.
> - @.@.IDENTITY will not work since I am not inserting a single row at a
> time
> - I guess I could INSERT INTO SecurityMaster first, THEN do another
> INSERT INTO Exchange_mm_SecurityMaster with different where clause.

The dangers of having too many IDENTITY columns.

You appear to have a natural key for both tables; use these for the
connection table too.

If you really need artificial keys, I would recommened skipping the
IDENTITY property. Instead take data through a temp table with an
IDENTITY column. Then determin the highest ID in use in the target
table, and now you can compute what keys the newly inserted rows
will have.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns93F31A3D90F4Yazorman@.127.0.0.1>...
> Jason (JayCallas@.hotmail.com) writes:
> > Now to the Exchange_mm_SecurityMaster. I need the individual identity
> > values for each row inserted into SecurityMaster so I can then turn
> > around and insert into Exchange_mm_SecurityMaster. Here are the
> > issues/possibilities as I see it.
> > - @.@.IDENTITY will not work since I am not inserting a single row at a
> > time
> > - I guess I could INSERT INTO SecurityMaster first, THEN do another
> > INSERT INTO Exchange_mm_SecurityMaster with different where clause.
> The dangers of having too many IDENTITY columns.

Huh. I am confused. Why is it too many?

I have only 2 IDENTITY columns -- one in SecurityMaster and another in
Exchanges.

The table Exchange_mm_SecurityMaster is for many-to-many entries. The
same security from SecurityMaster table can be on multiple exchanges
from Exchanges table.

> You appear to have a natural key for both tables; use these for the
> connection table too.

My problem is not which key I use. My problem is finding the best
approach to inserting many rows at once.

Or are you saying instead of using the IDENTITY columns, from
SecurityMaster and Exchanges, in Exchange_mm_SecurityMaster, use the
SYMBOL and EXCHANGE columns?

> If you really need artificial keys, I would recommened skipping the
> IDENTITY property. Instead take data through a temp table with an
> IDENTITY column. Then determin the highest ID in use in the target
> table, and now you can compute what keys the newly inserted rows
> will have.

Not sure how this would help.

(Just for my own information -- IF I did use the IDENTITY columns,
what would be the best approach to inserting into both tables?)

Thank you for your help in this matter.|||Jason (JayCallas@.hotmail.com) writes:
> Huh. I am confused. Why is it too many?
> I have only 2 IDENTITY columns -- one in SecurityMaster and another in
> Exchanges.

Since both tables appears to have natural one-column keys, I am not
convinced that using IDENTITY is called for.

> Or are you saying instead of using the IDENTITY columns, from
> SecurityMaster and Exchanges, in Exchange_mm_SecurityMaster, use the
> SYMBOL and EXCHANGE columns?

Yes.

>> If you really need artificial keys, I would recommened skipping the
>> IDENTITY property. Instead take data through a temp table with an
>> IDENTITY column. Then determin the highest ID in use in the target
>> table, and now you can compute what keys the newly inserted rows
>> will have.
> Not sure how this would help.

As I understood it, problem is that you say:

INSERT tbl_a (...)
SELECT ...
FROM src

INSERT tbl_b (...)
SELECT ...
FROM src

And now you are to insert into the relation table, but you don't know
what the keys are.

But since the natural keys come from the src, you could say:

INSERT tbl_c (a_ident, b_ident)
SELECT a.a_ident, b_ident
FROM src s
JOIN tbl_a ON a.a_narural_key = s.a_natural_key
JOIN tbl_b ON b.b_narural_key = s.b_natural_key

Provided that you have all information available. Since your post
only included sketches of what you are doing, it is difficult to
tell if this is entirely applicable.

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

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

Complex SQL Query

Well, at least I think it's complex! It might be easy for you!

I have the following 3 tables:

    ContentPages (Primary Key is PageID) stores information about pages, such as where the file is on the server, who created the page etc. ContentProtocols (PK is ProtocolID) stores the names of "protocols". In my content management system, a protocol is made up of a sequence of pages. So "Ben's Protocol" could be a sequence of "BensPage1.html", "BensPage2.html" and "BensPage3.aspx". The order of the pages is important. ContentProtocolsPages. This table stores pageIDs next to protocolIDs so that the pages are "in" protocols. It also stores the order of the pages.

ContentProtocolsPages has three columns:

    PageID (foreign key from ContentPages table) ProtocolID (FK from ContentProtocols table) Position. This is an integer column that stores the position of a page within a protocol, so the first page in a protocol has position 1. The second has position 2. The third has position 3 and so on.

The PageID and Position columns combine to make the primary key in the ContentProtocolPages table, because obviously you can't have more than one page occupying a given position in a protocol. e.g. You couldn't have "BenPage1.html" occupying "Ben's Protocol" position 2 and "BenPage2.html" occupying the same position in the same protocol.

The problem occurs when deleting a page.

The logic is:
Before a page can be deleted from the ContentPages table, it has to be taken out of any protocols, so all record with that page in ContentProtocolsPages have to be deleted. This means that any pages in the same protocol AFTER the deleted page need to have their position set to one less (Position=Position-1), to account for the page being removed. So, if you delete the page with position 3 in a six page protocol, the SQL statement has to set the pages with positions 4, 5 and 6 to be 3, 4 and 5 respecively.

You can't do that BEFORE deleting the record of the page in ContentProtocolsPages because that violates the primary key constraint, but you can't do it AFTER either, because then you have no idea what Position that page used to occupy.

Here's what I have so far, but I'm getting an error because of the composite primary key.

UPDATE ContentProtocolsPages
SET Position=Position-1
WHERE Position > (SELECT Position FROM ContentProtocolsPages WHERE PageID=@.PageID)
AND ProtocolID = (SELECT ProtocolID FROM ContentProtocolsPages WHERE PageID=@.PageID)

DELETE FROM ContentProtocolsPages WHERE PageID=@.PageID

DELETE FROM ContentPages WHERE PageID=@.PageID

Any Ideas? Many thanks to anybody who can help out with this problem

Yes absolutely. How silly of me. The ProtocolID and PositionID columns combine to make the Primary Key. Thanks very much for pointing that out. Any ideas regarding the problem, now correctly stated?
|||Ok. I thougt I had jumped the Conclusion. So I deleted the post. If you are using SQL SERVER 2005 try using the OUTPUT CLAUSE of delete statement.|||Thanks very much, but I'm afraid I've never heard of that. Can you recommend an article on how I should use it to achieve my purpose?
|||

you can also try an AFTER TRIGGER. Here is the sample code

ALTER TRIGGER MyDelTRG

ON [ContentProtocolsPages]

AFTER DELETE

AS

DECLARE @.MyDeleteCursor CURSOR

DECLARE @.PageID INT,@.ProtocolID INT,@.Position INT

-- Curosor Definition

SET @.MyDeleteCursor = CURSOR FAST_FORWARD

FOR

SELECT PageID,ProtocolID,Position FROM DELETED

OPEN @.MyDeleteCursor

FETCH NEXT FROM @.MyDeleteCursor

INTO @.PageID,@.ProtocolID,@.Position

--LOOP all records from the inserted table

WHILE @.@.FETCH_STATUS = 0

BEGIN

UPDATE ContentProtocolsPages SET Position=Position-1

WHERE Position>=@.Position

FETCH NEXT FROM @.MyDeleteCursor

INTO @.PageID,@.ProtocolID,@.Position

CLOSE @.MyDeleteCursor

DEALLOCATE @.MyDeleteCursor

END

|||That looks great! I don't understand it, but I'll try and learn it as I go along. On first inspection it looks like either of your suggestions could work. Do you recommend either in particular or doesn't it matter? Anyway, thanks for all your help, I'll see if I can put it into action.
Ben
|||Let me know if the code worked for you

Wednesday, March 7, 2012

complex 'query' using full text indexing

Hi people

i am having some difficulty with a quite advanced query (at least from my level).

select * from cities join areacodes on contains (city,'select area from areacodes right join cities on area not in (select city from cities)' )


Server: Msg 7631, Level 15, State 1, Line 1
Syntax error occurred near 'area'. Expected ''''' in search condition 'select area from areacodes right join cities on area not in (select city from cities)'.

what i am trying to do is find the areas in the postcodes table that contain words that are in the cities table. I need to match them up and modify the data in the postcodes table. the data is inconsistent as it comes from two unrelated sources. i have to be aware of spelling mistakes etc and have tried usind the soundex function to match them but it produces too many results. as you can see from the data in the postcodes table some areas (the second column) are not entirely upper case. these are the areas that have matched records in the cities table and the data is valid.

please can someone suggest the correct and easy way of doing this?

Thanks

Chris Morton

POSTCODES TABLE FIRST 30 ROWS

1

Aberdeen

49

3450

2

ABERDEEN FARM LINES

49212

3450

3

ABERFELDY

58652

3451

4

ACORNHOEK

13

3454

5

ACORNHOEK FARM LINES

137952

3454

6

Addo

42

3450

7

Adelaide

46

3450

8

Aggeneys

54

3456

9

AKASIA

12

3452

10

Albertinia

28

3458

11

Alberton

11

3452

12

ALETTASRUS

53922

3451

13

Alexander Bay

27

3456

14

Alexandria

46

3450

15

Alice

40

3450

16

ALICE FARM LINES

4049

3450

17

ALICEDALE

42

3450

18

Aliwal North

51

3450

19

Allanridge

57

3451

20

Alldays

15

3457

21

ALMA

14

3455

22

Amalia

53

3455

23

AMANDEBULT

14

3455

24

Amanzimtoti

31

3453

25

AMATIKULU

35

3453

26

Amersfoort

17

3454

27

Amsterdam

17

3454

28

ANERLEY

39

3453

29

APEL

15

3457

30

APEL FARM LINES

15482

3457

CITIES TABLE FIRST 30 ROWS

1

Aberdeen

3450

2

Addo

3450

3

Adelaide

3450

4

Alexandria

3450

5

Alice

3450

6

Aliwal North

3450

7

Balfour

3450

8

Barkly East

3450

9

Bathurst

3450

10

Bedford

3450

11

Bisho

3450

12

Burgersdorp

3450

13

Butterworth

3450

14

Cathcart

3450

15

Cintsa

3450

16

Coffee Bay

3450

17

Cookhouse

3450

18

Cradock

3450

19

Dordrecht

3450

20

East London

3450

21

Elliot

3450

22

Flagstaff

3450

23

Fort Beaufort

3450

24

Gonubie

3450

25

Graaff Reinet

3450

26

Grahamstown

3450

27

Haga-Haga

3450

28

Hamburg

3450

29

Hankey

3450

30

Herschel

3450

Hi Chris,

The only way I can think of that you can leverage CONTAINS/fulltext functionality in this case is unfortunately through a cursor - you'll need to fetch a row from the Cities table and run a CONTAINS query on your Postcodes table per every city you fetch.

If you have a requiement for matching large amounts of "fuzzy" data, you may want to check if Fuzzy Lookup Transform in SSIS could be useful.

Hope this helps.

Best regards,

Saturday, February 25, 2012

Complex Query - at least for me

I've been trying to do this on and off for over a month, just can't seem to
get it. I have a table that looks something like
Name Activity
==== ======== Mike Arrest
John Victim
Fred Suspect
John Suspect
Mike Victim
John Victim
Mike Arrest
For graphing purposes, I'd like to end up with a view that looks like
Name Victim_Count Arrest_Count Suspect_Count
==== ============ ============ ============= Mike 1 2 0
John 2 0 1
Fred 0 0 1
I've tried things like select name, (select count(*) where activity = 'Victim') as Victim_Count group by name. Which doesn't work.
Can anyone point me in the right direction? I know there are fixed number of
Activity types (3 in this case).
Any help is much appreciated,
MikeSELECT [name],
COUNT(CASE activity WHEN 'victim' THEN 1 END) AS victim_count,
COUNT(CASE activity WHEN 'arrest' THEN 1 END) AS arrest_count,
COUNT(CASE activity WHEN 'suspect' THEN 1 END) AS suspect_count
FROM Sometable
GROUP BY [name]
--
David Portas
--
Please reply only to the newsgroup
--|||This is a multi-part message in MIME format.
--=_NextPart_000_0185_01C3CF8B.993AB0B0
Content-Type: text/plain;
charset="Windows-1252"
Content-Transfer-Encoding: 7bit
Try:
select
Name
, sum (case when Activity = 'Victim' then 1 else 0 end) as Victim_Count
, sum (case when Activity = 'Arrest' then 1 else 0 end) as Arrest_Count
, sum (case when Activity = 'Suspect' then 1 else 0 end) as Suspect_Count
from
MyTable
group by
Name
--
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Mike Hildner" <mhildner@.afweb.com> wrote in message
news:Ofw7lO7zDHA.2456@.TK2MSFTNGP12.phx.gbl...
I've been trying to do this on and off for over a month, just can't seem to
get it. I have a table that looks something like
Name Activity
==== ========Mike Arrest
John Victim
Fred Suspect
John Suspect
Mike Victim
John Victim
Mike Arrest
For graphing purposes, I'd like to end up with a view that looks like
Name Victim_Count Arrest_Count Suspect_Count
==== ============ ============ =============Mike 1 2 0
John 2 0 1
Fred 0 0 1
I've tried things like select name, (select count(*) where activity ='Victim') as Victim_Count group by name. Which doesn't work.
Can anyone point me in the right direction? I know there are fixed number of
Activity types (3 in this case).
Any help is much appreciated,
Mike
--=_NextPart_000_0185_01C3CF8B.993AB0B0
Content-Type: text/html;
charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Try:
select
=Name
, sum (case =when Activity =3D 'Victim' then 1 else 0 end) as Victim_Count
, sum =(case when Activity =3D 'Arrest' then 1 else 0 end) as Arrest_Count
, sum (case =when Activity =3D 'Suspect' then 1 else 0 end) as Suspect_Count
from
MyTable
group by
Name
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Mike Hildner" wrote in =message news:Ofw7lO7zDHA.2456=@.TK2MSFTNGP12.phx.gbl...I've been trying to do this on and off for over a month, just can't seem =toget it. I have a table that looks something likeName Activity=3D=3D=3D=3D &=nbsp; =3D=3D=3D=3D=3D=3D=3D=3DMike  =; ArrestJohn VictimFred SuspectJohn SuspectMike VictimJohn VictimMike ArrestFor graphing purposes, I'd like to end up with a view that =looks likeName Victim_Count Arrest_Count Suspect_Count=3D=3D=3D=3D &n=bsp; =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D &=nbsp; =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D &=nbsp; =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DMike &n=bsp; 1 = 2 = 0John 2 = 0 = 1Fred 0 = 0 = 1I've tried things like select name, (select count(*) where =activity =3D'Victim') as Victim_Count group by name. Which doesn't =work.Can anyone point me in the right direction? I know there are fixed number ofActivity types (3 in this case).Any help is much appreciated,Mike

--=_NextPart_000_0185_01C3CF8B.993AB0B0--|||Tom and David,
Sincere thanks. Both methods seem to produce the same result - exactly what
I need. If you only knew the trouble I was having. Gives me something to
read up on.
Much appreciated,
Mike
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:UtmdnWcR0ITBcm-i4p2dnA@.giganews.com...
> SELECT [name],
> COUNT(CASE activity WHEN 'victim' THEN 1 END) AS victim_count,
> COUNT(CASE activity WHEN 'arrest' THEN 1 END) AS arrest_count,
> COUNT(CASE activity WHEN 'suspect' THEN 1 END) AS suspect_count
> FROM Sometable
> GROUP BY [name]
> --
> David Portas
> --
> Please reply only to the newsgroup
> --
>|||Greetings...
Is there a way to do this type of Query from the View designer or must I do
it from query analyzer'
Thanks!
S.
"Mike Hildner" <mhildner@.afweb.com> wrote in message
news:Ofw7lO7zDHA.2456@.TK2MSFTNGP12.phx.gbl...
> I've been trying to do this on and off for over a month, just can't seem
to
> get it. I have a table that looks something like
> Name Activity
> ==== ========> Mike Arrest
> John Victim
> Fred Suspect
> John Suspect
> Mike Victim
> John Victim
> Mike Arrest
> For graphing purposes, I'd like to end up with a view that looks like
> Name Victim_Count Arrest_Count Suspect_Count
> ==== ============ ============ =============> Mike 1 2 0
> John 2 0 1
> Fred 0 0 1
> I've tried things like select name, (select count(*) where activity => 'Victim') as Victim_Count group by name. Which doesn't work.
> Can anyone point me in the right direction? I know there are fixed number
of
> Activity types (3 in this case).
> Any help is much appreciated,
> Mike
>