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

Tuesday, March 27, 2012

attach db

How can I attach a remote db via Enterprise Manager or Query Analyzer?
Am I wrong if I launch a "sp_attach" sql file (from my local machine) to the remote server?
Do I really have to detach local db before?
Please can someone just tell me how he did?

SaoriHi saori,
1. Did you try to post your question in the DBA section of these forums:

http://www.sqlteam.com/Forums/


http://www.sql-server-performance.com/forum/default.asp

2. Hope some DBA will help you.|||Thanks for the answer.
I'll (quickly) give it a try.

(I posted a msg there 'cause it is above all a question of method about sql server tools)

Saori|||Honestly, I attach remote db's by creating a new registration. Unless you mean something else like fiberchanneling or something, but as for having your SQL Enterprise Manager utilize a Remote SQL Server, just create a new registration.

For T-SQL based methods, you're not necessarily attaching. I'd say it's more Linked Server, or Using Remote Servers. check books online for those two in the Index tab.

SP_LinkedServers and the other method would be actually using the enterprise manager to create the registration.|||Saori,

You didn't clearly define your question about what you want to 'attach', but I think I have understood what you were saying. I would redefine your question with several possible solutions.

Assume, you have a local SQL server in your machine, and there is another SQL server in a remote machine. There is a database called pubs1 existing in the remote SQL server. You want it APPEARS ('attach') in your SQL server.

1. Logical APPEAR:
As KraGiE suggested you could make a new Server Registration in your local SQL Enterprise Manager to LINK to that remote SQL server. In this way, you would bring the whole SQL server including the pubs1 into your local SQL Enterprise Manager.

However, to do so, you need to have the access to the database, say: machine name, login name and password. It is possible that you could only access one database in that server, say, pubs1. But that is enough for you. By the way, if the remote server is not within your LAN, and need to be linked through HTTP, you should have the server IP address and also the access to possible firewall.

I called this kind of 'attach' as logical APPEARS, because the database is not physically in your machine, but still at the remote server. You can only access the database through your Enterprise Manager. The database pubs1 appearing in your Enterprise Manager is just a pointer linked to the remote server.

2. Physical APPEAR:
In short, get a physical copy from the remote server and 'attach' it to your local server.

Step 1:
Copy the database file and the log file into your local machine. In this case, pubs1 files are located by default at:
C:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs1.MDF
C:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs1_log.LDF
You need shut down the remote database for copy/past, otherwise, it wouldn't work.

Step 2:
from Enterprise Manager, right click the Databases object in your local SQL instance, choose all tasks --> attach database ... . From the Attach Database window, choose your database file, pubs1, and then OK.

3. If you didn't have SQL 2000, instead of SQL 7.0, then the Step 2 would not avaiable in Enterprise Manager. You would have to use the command 'sp_attach_db' to do the job. Something like:


EXEC sp_attach_db @.dbname = N'pubs',
@.filename1 = N'c:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs1.mdf',
@.filename2 = N'c:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs_log1.ldf'

4. Finally, if you even didn't have SQL server 7.0, you couldn't do the trick of 'attach'. But, you could do the job with SQL server 6.5 Enterprise Manager 'Database/Object transfer' tool given you have access to the remote database, where there is equivalent tools in both SQL 7.0/2000, called Import Data/Export Data, but not as easy used as the ATTACH method.

Hope this helps.|||Thanks Phuoc, KraGiE and ghan.
This really helped me understand essential issues.

Great analysis , ghan (copied in my notepad)!
Just one little thing:
When I attach db via Enterprise Manager, do I automatically transfer log file as well?|||saori,

I am really happy to hear that. You know what, when I made some analyses to other people, I just summarize what I have done and clear my understanding about this issue myself.

When I attach db via Enterprise Manager, do I automatically transfer log file as well?

You see the example:


EXEC sp_attach_db @.dbname = N'pubs',
@.filename1 = N'c:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs1.mdf',
@.filename2 = N'c:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs_log1.ldf'

There are two files, one is *.mdf, the data file, another is *.ldf, the log file.

When you use enterprise manager to do the job, you will see, (at STEP 2) you only need browse the *.mdf file in, while the *.ldf file will be brought in automatically, assuming you have copied the two files into the same directory (Step 1).

Good luck.|||I have a project lets say project1. I have a copy of it running on my development server and a copy of it on my production server. I have detached db from development server and attached it to my production server. I can work in db using Enterprise manager but when I try to run my applications it doesnt work. I know why it doesnt work its because its looking for user developmentserver and now its on productionserver. Is there a way to set permissions for user productionserver without having to do every table and stored procedure one at a time? I would like to do it quickly and efficiently and doing all by hand one at a time is neither.
Please help.|||There is a security issue. You must use Windows Authentification, instead of SQL Server Authentification. You might change your connection string to use SQL Server authentification. If you want to keep to use windows authentification, you need to setup your security in your production server to make your application assistent with your SQL server.

Sunday, March 25, 2012

Attach and ODBC Database in Enterprise Manger (I think)

I have created an SQL database and would like to attach an ODBC database so
I can query its data along with data from the SQL database. How can I
attached this table in the Enterprise manager? Or maybe my thinking is
wrong and can't be done this way, so how do i do it? Sotred Procedures?
Views? Please help...
Thank you in advance for any help for I am in a real bind,
MikeI think what you are saying is you want to connect an ODBC datasource to you
r
SQL database. Is this correct?
"Michael Kintner" wrote:

> I have created an SQL database and would like to attach an ODBC database s
o
> I can query its data along with data from the SQL database. How can I
> attached this table in the Enterprise manager? Or maybe my thinking is
> wrong and can't be done this way, so how do i do it? Sotred Procedures?
> Views? Please help...
> Thank you in advance for any help for I am in a real bind,
> Mike
>
>|||Use can use Enterprise Manager to create a Linked Server. In the EM,
expand your database instance, then expand the Security node and then
right click on Linked Servers to create a new linked server. Fill-in
the blanks and you're done.
In Query Analyzer, you can query you linked server like:
select * from <linked_server_name>.<database_name>.<dbo>.<table_name>
Easy.|||YEs this is correct, I have an AS400 system I would like connect to my SQL
server and run views between both systems on my SQL server.
"Lontae Jones" <LontaeJones@.discussions.microsoft.com> wrote in message
news:2A5BEF15-D324-43AB-81A9-954257D496DD@.microsoft.com...
>I think what you are saying is you want to connect an ODBC datasource to
>your
> SQL database. Is this correct?
>
>
> "Michael Kintner" wrote:
>

Thursday, March 22, 2012

Asynchrous query

I have a query that because the database is across the country it takes time
to bring a large amount of data to the client executing a command. I was
wondering if there was a way to execute an asychronus command? Ideally I
would like to get periodic feedback on the progress. I am sure that most of
the delay is network related but it is hard to tell how close to finishing a
command is by just executing the ExecuteScalar from a SQL command.
Thank you for your suggestions.
KevinOn Sat, 8 Jul 2006 16:25:01 -0700, Kevin Burton
<KevinBurton@.discussions.microsoft.com> wrote:
>I have a query that because the database is across the country it takes tim
e
>to bring a large amount of data to the client executing a command. I was
>wondering if there was a way to execute an asychronus command? Ideally I
>would like to get periodic feedback on the progress. I am sure that most of
>the delay is network related but it is hard to tell how close to finishing
a
>command is by just executing the ExecuteScalar from a SQL command.
>Thank you for your suggestions.
Easiest way is probably to create the extra thread in your app code.
Don't know any standard way of monitoring progress.
If you program down at the ODBC/dblib level (is that still even
possible on SQL2005?), with server-side cursors, then you can monitor
progress. But it's a lot of work! Hmm, I suppose, in that extra
thread of yours, you could use server-side cursors and monitor it even
at the OLEDB level!
What language is your client written in?
(Does OLEDB support async queries? I don't know, I've been writing
nothing but TSQL for too long now!)
Josh|||ADO.NET 2.0 has asynchronous operations, like BeginExecuteReader and EndExec
uteReader, etc. Doesn't
seem to be a BeginExecuteScalar, though.
But you should carefully consider in what way you want the execution to be a
synchronous.
If you use any of above mentioned methods, you cannot read off of the result
s until the whole set
has been passed to the client.
Using a regular ExecuteReader, you can read the results as they are sent to
the client. You don't
have to wait for the whole set until you can present data to the end user. N
ote that SQL Server can
use worktables and don't send the result until it is done, depending on the
execution plan. A FAST
hint can be useful, but that can increase the total query cost (sometimes ra
dically).
Above doesn't matter for a ExecuetScalar, of course, but it can be important
when reading a number
of rows.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
news:1417C3D0-681F-4DC0-9F4F-38DB3C2F8DCE@.microsoft.com...
>I have a query that because the database is across the country it takes tim
e
> to bring a large amount of data to the client executing a command. I was
> wondering if there was a way to execute an asychronus command? Ideally I
> would like to get periodic feedback on the progress. I am sure that most o
f
> the delay is network related but it is hard to tell how close to finishing
a
> command is by just executing the ExecuteScalar from a SQL command.
> Thank you for your suggestions.
> Kevin|||Thank you for the tip. My client is written in .NET. I guess I was hoping
for some access to the network as I indicated before the physical database
resides a long way away so I am suspecting that the actual query is probably
quick enough it is just tranferring the data across the network that takes
the time. The thing of it is that I what the code somehow to adjust for the
long distance data transfer. I can't do that as far as I can see without
knowing about the network being used to transfer the data. Anyway, thanks
again. If the bottle neck does in fact prove to be the SQL query then I will
look into your suggestions.
Kevin|||I started to look at these calls and it brought up another question. The dat
a
that is being read is a column with XML data. It is typed 'text' and the
server is running 2000 so I don't have an option to type the column as XML.
I
would however like to use ExecuteXmlReader but I get an exception indicatin
g
that the data must be XML. How do I convince the client that it is XML data?
My current query looks like:
SELECT XMLSent FROM dbo.OutboundTable WHERE documentTransactionID=xxx AND
OrderNumber='yyy'
It seems silly to read in a large chunk of "string" data, pass it to a
MemoryStream, build an XmlReader, and then use that to build an XML document
(specifically an XPath document because I want to do some XPath searches on
the data). If I can get an XmlReader directly from the SQL query via
ExecuteXmlReader it seems more efficient. Is this possible with the data
structured as I indicated?
Thank you.
Kevin
"Tibor Karaszi" wrote:

> ADO.NET 2.0 has asynchronous operations, like BeginExecuteReader and EndEx
ecuteReader, etc. Doesn't
> seem to be a BeginExecuteScalar, though.
> But you should carefully consider in what way you want the execution to be
asynchronous.
> If you use any of above mentioned methods, you cannot read off of the resu
lts until the whole set
> has been passed to the client.
> Using a regular ExecuteReader, you can read the results as they are sent t
o the client. You don't
> have to wait for the whole set until you can present data to the end user.
Note that SQL Server can
> use worktables and don't send the result until it is done, depending on th
e execution plan. A FAST
> hint can be useful, but that can increase the total query cost (sometimes
radically).
> Above doesn't matter for a ExecuetScalar, of course, but it can be importa
nt when reading a number
> of rows.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
> news:1417C3D0-681F-4DC0-9F4F-38DB3C2F8DCE@.microsoft.com...
>|||That is a bit too high in the API stack for me to be able to comment on. Per
haps FOR XML in the
query would allow you to type it as XML? I suggest you post this to an ADO.N
ET group, unless someone
jump in here with more specific recommendations.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
news:9342A66A-B585-4890-8E8B-719114510350@.microsoft.com...[vbcol=seagreen]
>I started to look at these calls and it brought up another question. The da
ta
> that is being read is a column with XML data. It is typed 'text' and the
> server is running 2000 so I don't have an option to type the column as XML
. I
> would however like to use ExecuteXmlReader but I get an exception indicat
ing
> that the data must be XML. How do I convince the client that it is XML dat
a?
> My current query looks like:
> SELECT XMLSent FROM dbo.OutboundTable WHERE documentTransactionID=xxx AND
> OrderNumber='yyy'
> It seems silly to read in a large chunk of "string" data, pass it to a
> MemoryStream, build an XmlReader, and then use that to build an XML docume
nt
> (specifically an XPath document because I want to do some XPath searches o
n
> the data). If I can get an XmlReader directly from the SQL query via
> ExecuteXmlReader it seems more efficient. Is this possible with the data
> structured as I indicated?
> Thank you.
> Kevin
> "Tibor Karaszi" wrote:
>sql

Asynchrous query

I have a query that because the database is across the country it takes time
to bring a large amount of data to the client executing a command. I was
wondering if there was a way to execute an asychronus command? Ideally I
would like to get periodic feedback on the progress. I am sure that most of
the delay is network related but it is hard to tell how close to finishing a
command is by just executing the ExecuteScalar from a SQL command.
Thank you for your suggestions.
KevinOn Sat, 8 Jul 2006 16:25:01 -0700, Kevin Burton
<KevinBurton@.discussions.microsoft.com> wrote:
>I have a query that because the database is across the country it takes time
>to bring a large amount of data to the client executing a command. I was
>wondering if there was a way to execute an asychronus command? Ideally I
>would like to get periodic feedback on the progress. I am sure that most of
>the delay is network related but it is hard to tell how close to finishing a
>command is by just executing the ExecuteScalar from a SQL command.
>Thank you for your suggestions.
Easiest way is probably to create the extra thread in your app code.
Don't know any standard way of monitoring progress.
If you program down at the ODBC/dblib level (is that still even
possible on SQL2005?), with server-side cursors, then you can monitor
progress. But it's a lot of work! Hmm, I suppose, in that extra
thread of yours, you could use server-side cursors and monitor it even
at the OLEDB level!
What language is your client written in?
(Does OLEDB support async queries? I don't know, I've been writing
nothing but TSQL for too long now!)
Josh|||ADO.NET 2.0 has asynchronous operations, like BeginExecuteReader and EndExecuteReader, etc. Doesn't
seem to be a BeginExecuteScalar, though.
But you should carefully consider in what way you want the execution to be asynchronous.
If you use any of above mentioned methods, you cannot read off of the results until the whole set
has been passed to the client.
Using a regular ExecuteReader, you can read the results as they are sent to the client. You don't
have to wait for the whole set until you can present data to the end user. Note that SQL Server can
use worktables and don't send the result until it is done, depending on the execution plan. A FAST
hint can be useful, but that can increase the total query cost (sometimes radically).
Above doesn't matter for a ExecuetScalar, of course, but it can be important when reading a number
of rows.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
news:1417C3D0-681F-4DC0-9F4F-38DB3C2F8DCE@.microsoft.com...
>I have a query that because the database is across the country it takes time
> to bring a large amount of data to the client executing a command. I was
> wondering if there was a way to execute an asychronus command? Ideally I
> would like to get periodic feedback on the progress. I am sure that most of
> the delay is network related but it is hard to tell how close to finishing a
> command is by just executing the ExecuteScalar from a SQL command.
> Thank you for your suggestions.
> Kevin|||Thank you for the tip. My client is written in .NET. I guess I was hoping
for some access to the network as I indicated before the physical database
resides a long way away so I am suspecting that the actual query is probably
quick enough it is just tranferring the data across the network that takes
the time. The thing of it is that I what the code somehow to adjust for the
long distance data transfer. I can't do that as far as I can see without
knowing about the network being used to transfer the data. Anyway, thanks
again. If the bottle neck does in fact prove to be the SQL query then I will
look into your suggestions.
Kevin|||I started to look at these calls and it brought up another question. The data
that is being read is a column with XML data. It is typed 'text' and the
server is running 2000 so I don't have an option to type the column as XML. I
would however like to use ExecuteXmlReader but I get an exception indicating
that the data must be XML. How do I convince the client that it is XML data?
My current query looks like:
SELECT XMLSent FROM dbo.OutboundTable WHERE documentTransactionID=xxx AND
OrderNumber='yyy'
It seems silly to read in a large chunk of "string" data, pass it to a
MemoryStream, build an XmlReader, and then use that to build an XML document
(specifically an XPath document because I want to do some XPath searches on
the data). If I can get an XmlReader directly from the SQL query via
ExecuteXmlReader it seems more efficient. Is this possible with the data
structured as I indicated?
Thank you.
Kevin
"Tibor Karaszi" wrote:
> ADO.NET 2.0 has asynchronous operations, like BeginExecuteReader and EndExecuteReader, etc. Doesn't
> seem to be a BeginExecuteScalar, though.
> But you should carefully consider in what way you want the execution to be asynchronous.
> If you use any of above mentioned methods, you cannot read off of the results until the whole set
> has been passed to the client.
> Using a regular ExecuteReader, you can read the results as they are sent to the client. You don't
> have to wait for the whole set until you can present data to the end user. Note that SQL Server can
> use worktables and don't send the result until it is done, depending on the execution plan. A FAST
> hint can be useful, but that can increase the total query cost (sometimes radically).
> Above doesn't matter for a ExecuetScalar, of course, but it can be important when reading a number
> of rows.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
> news:1417C3D0-681F-4DC0-9F4F-38DB3C2F8DCE@.microsoft.com...
> >I have a query that because the database is across the country it takes time
> > to bring a large amount of data to the client executing a command. I was
> > wondering if there was a way to execute an asychronus command? Ideally I
> > would like to get periodic feedback on the progress. I am sure that most of
> > the delay is network related but it is hard to tell how close to finishing a
> > command is by just executing the ExecuteScalar from a SQL command.
> >
> > Thank you for your suggestions.
> >
> > Kevin
>|||That is a bit too high in the API stack for me to be able to comment on. Perhaps FOR XML in the
query would allow you to type it as XML? I suggest you post this to an ADO.NET group, unless someone
jump in here with more specific recommendations.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
news:9342A66A-B585-4890-8E8B-719114510350@.microsoft.com...
>I started to look at these calls and it brought up another question. The data
> that is being read is a column with XML data. It is typed 'text' and the
> server is running 2000 so I don't have an option to type the column as XML. I
> would however like to use ExecuteXmlReader but I get an exception indicating
> that the data must be XML. How do I convince the client that it is XML data?
> My current query looks like:
> SELECT XMLSent FROM dbo.OutboundTable WHERE documentTransactionID=xxx AND
> OrderNumber='yyy'
> It seems silly to read in a large chunk of "string" data, pass it to a
> MemoryStream, build an XmlReader, and then use that to build an XML document
> (specifically an XPath document because I want to do some XPath searches on
> the data). If I can get an XmlReader directly from the SQL query via
> ExecuteXmlReader it seems more efficient. Is this possible with the data
> structured as I indicated?
> Thank you.
> Kevin
> "Tibor Karaszi" wrote:
>> ADO.NET 2.0 has asynchronous operations, like BeginExecuteReader and EndExecuteReader, etc.
>> Doesn't
>> seem to be a BeginExecuteScalar, though.
>> But you should carefully consider in what way you want the execution to be asynchronous.
>> If you use any of above mentioned methods, you cannot read off of the results until the whole set
>> has been passed to the client.
>> Using a regular ExecuteReader, you can read the results as they are sent to the client. You don't
>> have to wait for the whole set until you can present data to the end user. Note that SQL Server
>> can
>> use worktables and don't send the result until it is done, depending on the execution plan. A
>> FAST
>> hint can be useful, but that can increase the total query cost (sometimes radically).
>> Above doesn't matter for a ExecuetScalar, of course, but it can be important when reading a
>> number
>> of rows.
>> --
>> Tibor Karaszi, SQL Server MVP
>> http://www.karaszi.com/sqlserver/default.asp
>> http://www.solidqualitylearning.com/
>>
>> "Kevin Burton" <KevinBurton@.discussions.microsoft.com> wrote in message
>> news:1417C3D0-681F-4DC0-9F4F-38DB3C2F8DCE@.microsoft.com...
>> >I have a query that because the database is across the country it takes time
>> > to bring a large amount of data to the client executing a command. I was
>> > wondering if there was a way to execute an asychronus command? Ideally I
>> > would like to get periodic feedback on the progress. I am sure that most of
>> > the delay is network related but it is hard to tell how close to finishing a
>> > command is by just executing the ExecuteScalar from a SQL command.
>> >
>> > Thank you for your suggestions.
>> >
>> > Kevin
>>

Tuesday, March 20, 2012

associated xsl file will not format working xml template

I am just trying to get (what I thought was) a simple xsl file to
format (--> HTML) a simple xml query specified in a template file.
I do not get any message in the browser (except: page not found) or in
the Windows event viewer.
I am able to execute a URL query with no problems.
I am able to execute the template query.
When I specifiy the xsl file, no information appears.
I would like to know where/how this type of problem can be debugged.
I would be happy to post the short xml and xsl file here if that could
illuminate this problem.
TIA.
Regards..
"Relishguy" <dbsearch04@.yahoo.com> wrote in message
news:84e6fe3d.0406140716.15af040a@.posting.google.c om...
[snip]
> I would like to know where/how this type of problem can be debugged.
The best way to debug this type of problem is to debug the xsl since that is
usually where the problem is. You can post it here if you want and I would
also suggest saving an XML file that has the results from your query and
then linking the stylesheet to it and opening it in IE.
Bryant
sql

Monday, March 19, 2012

assistance with sql query

Thanks in advance, I am trying to display the count of uptimes and downtimes in a single query. i started with something like
SELECT DISTINCT servername,
(SELECT COUNT(*)
FROM pingtable
WHERE (status = '0')) AS Uptime,
(SELECT COUNT(*)
FROM pingtable
WHERE (status <> '0')) AS DownTime
FROM pingtable

but this gives me the
server1 7 2
server1 7 2
...

Table layout and data:
servername status

server1 up
server1 up
server1 down
server2 up
server2 up
server2 up
server3 down
server3 up
server3 up

the output I would like to have is

Server UpCount DownCount
Server1 2 1
Server2 3 0
Server3 2 1Lookup crosstab queries in books online. Near the bottom is some sample code you can modify for your needs.

You'll end up with something like this:

Select Server,
sum(Case Status when 0 then 1 else 0) Uptime,
sum(Case Status when <> 0 then 1 else 0) Downtime
From PingTable
Group by Server

I'm not sitting at a server console now, so I had to draft it from memory and it probably has syntax errors in it, but you should be able to get the idea.

blindman|||Thanks so much for holding my hand there,
Here is the final query that worked perfectly
Select Server,
sum(Case Status when 0 then 1 else 0 end) as Uptime,
sum(Case Status when 0 then 0 else 1 end) as Downtime
From eladmin.PingstatsNT
Group by Server

Originally posted by blindman
Lookup crosstab queries in books online. Near the bottom is some sample code you can modify for your needs.

You'll end up with something like this:

Select Server,
sum(Case Status when 0 then 1 else 0) Uptime,
sum(Case Status when <> 0 then 1 else 0) Downtime
From PingTable
Group by Server

I'm not sitting at a server console now, so I had to draft it from memory and it probably has syntax errors in it, but you should be able to get the idea.

blindman|||FYI, if your Status field always holds zeros or ones, set it's data type to bit to ensure that your code will always work correctly.

blindman

Assistance with selecting first visit record of patients

Hi all

I saw a similar query on another thread but was unable to use the answers to resolve my problem.

I have an access database with two tables - the first contains demographic data for patients (Initial visit table) and the second (followup visit) contains all visit records for these patients linked by a PID. Some of the data was entered retrospectively so the record number is not a reflection of date of visit. Have 25000 visits captured.

I need to devise a query to extract the first CD4 count (a blood result) available for each patient - cd4 not done on every visit. Have tried using:

SELECT InitialVisitID, VisitDatetime, CD4CountPercentage

FROM [FollowUpVisit] AS a

WHERE (((a.InitialVisitID)=(select top 1 InitialVisitID from [FollowUpVisit]b

where a.InitialVisitID = b.InitialVisitID

order by VisitDatetime desc)));

This initially generates a table with duplicates followed shortly thereafter by a warning that only one record can be returned by the subquery and then blanking out of all records in the query output.

Please help!

I believe you want something like this:

SELECT a.InitialVisitID, a.VisitDatetime, a.CD4CountPercentage

FROM FollowUpVisit a

inner join

(select Min(InitialVisitID) as InitialVisitID, VisitDatetime, CD4CountPercentage

from FollowUpVisit

group by InitialVisitID

) as b

on a.InitialVisitID = b.InitialVisitID

order by a.VisitDatetime desc

|||

Try:

SELECT InitialVisitID, VisitDatetime, CD4CountPercentage

FROM [FollowUpVisit] AS a

WHERE (((a.InitialVisitID)=(select top 1 InitialVisitID from [FollowUpVisit] b

where b.PID = a.PID

order by VisitDatetime desc)));

AMB

|||

Thanks for the quick response AMB

Your suggestion has the same result - except asks for the PID paramter to be entered.

Just for clarification InitialVisitID in this database is in fact the PID. So i tried it with changing PID to InitialVisitID but same outcome.

h

|||

Thanks for the response

For clarification the "InitialVisitId" is the PID - so selecting for min InitialVisitID does not work as every patient only has one InitialVisitID (is unique identifier and primary key). Your solution also gives a circular reference problem within the Selection list. Tried making it:

SELECT a.InitialVisitID, a.VisitDatetime, a.CD4CountPercentage
FROM FollowUpVisit a
inner join
(select Min(VisitDateTime) as VisitDateTime, InitialVisitID, CD4CountPercentage
from FollowUpVisit
group by InitialVisitID
) as b
on a.InitialVisitID = b.InitialVisitID
order by a.VisitDatetime desc

but got same problem

h

|||

Please, do not make us to guess your enviroment. Post some DDL, including constraints and indexes, sample data and expected result.

Can you post the error msg you are getting?. I do not think that (select top 1 c1, ..., cn from ... order by) can bring more than one row, without using keywords WITH TIES.

AMB

|||

I am confused by this table FollowUpVisit. If this was a Visit table, I might understand, but is the InitialVisit stored in the FollowUpVisit table?

And this seems to imply that you can have >1 InitialVisit?

In your query, be sure and use aliases for every column, just to be careful with the output:

SELECT a.InitialVisitID, a.VisitDatetime, a.CD4CountPercentage

FROM [FollowUpVisit] AS a

WHERE (((a.InitialVisitID)=(select top 1 b.InitialVisitID from [FollowUpVisit] b

where a.InitialVisitID = b.InitialVisitID

order by b.VisitDatetime desc)));

I agree with Hunchback, in that I don't know how that top 1 query can return > 1 row.

Assistance with error message

I am trying to run this script in Query Analyser and it seems to have a
problem in line 3:
-
select ID, 9, '2004', (select id from type where type = 'MF') from Dept
where dept in ('Internal Medicine', 'Surgery')
and ID + (select id from type where type = 'MF') +
convert(varchar(2), 9) +
convert(varchar(4), '2004')
not in
(select m.deptID + m.typeid + convert(varchar(2), m.dtmonth) +
convert(varchar(4), m.dtyear) from monthdept m, dept d, type t
where m.DeptID *= d.ID
and m.TypeID *= t.Type
)
The error message is: Invalid operator for data type. Operator equals add,
type equals uniqueidentifier.
I have tried playing with CAST/CONVERT without success. I am trying to look
for records on a key that spans 4 fields. Any suggestions/thoughts?
Schoo
PS: SQL Server 2000 running on W2K Server
Hi Schoo,
From your descriptions, I understood that the following codes raise an
error in QA, correct me if I was wrong, however, when I copied codes you
provided to my QA and then Parse Query (Ctrl + F5), it passed. To make
further research on this issue, I would appreciated if you could provide me
detailed DDL of your database and some sample record for me to reporduce it
on my machine. One more question, have you upgraded to the latest SQL
Server Service Pack?
Here is the document on how to get DDL from Enterprise Manager
Please provide DDL and sample data.
http://www.aspfaq.com/etiquette.asp?id=5006
Thank you for your patience and corperation. If you have any questions or
concerns, don't hesitate to let me know. We are here to be of assistance!
Sincerely yours,
Mingqing Cheng
Online Partner Support Specialist
Partner Support Group
Microsoft Global Technical Support Center
Introduction to Yukon! - http://www.microsoft.com/sql/yukon
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only, many thanks!

Assistance with a query

I have 2 tables POheader and POline. I am running the following SQL
statement but am getting 2 records where as I should only be getting one.
Could someone please assist.
s_commar@.hotmail.com
select POheader.ponbr from POheader inner join POline on POheader.Ponbr =
POline.Ponbr and POline.ponbr
= 16916;
I should just be getting one record but I get 2 records. Could someone
advise as to what I am doing wrong.
Thanks
s_commar@.hotmail.comIts hard to comment without seeing DDL+Sample data. My best
guess is that your POline table has 2 matching rows. If you dont want to
reference any columns from the POnline table in the final output,
you can probably rewrite your query like
Select POheader.ponbr from POheader
WHERE EXISTS(
SELECT 1 FROM POline WHERE POheader.Ponbr = POline.Ponbr
AND POline.ponbr = 16916)
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"s commar" <scommar@.verizon.net> wrote in message
news:36iJe.1262$D4.785@.trndny07...
>I have 2 tables POheader and POline. I am running the following SQL
>statement but am getting 2 records where as I should only be getting one.
>Could someone please assist.
> s_commar@.hotmail.com
>
> select POheader.ponbr from POheader inner join POline on POheader.Ponbr =
> POline.Ponbr and POline.ponbr
> = 16916;
>
> I should just be getting one record but I get 2 records. Could someone
> advise as to what I am doing wrong.
> Thanks
> s_commar@.hotmail.com
>|||"s commar" schrieb:

> I have 2 tables POheader and POline. I am running the following SQL
> statement but am getting 2 records where as I should only be getting one.
> Could someone please assist.
> s_commar@.hotmail.com
> select POheader.ponbr from POheader inner join POline on POheader.Ponbr =
> POline.Ponbr and POline.ponbr
> = 16916;
> I should just be getting one record but I get 2 records. Could someone
> advise as to what I am doing wrong.
> Thanks
> s_commar@.hotmail.com
select POheader.ponbr
from POheader
inner join POline
on POheader.Ponbr = POline.Ponbr
WHERE POline.ponbr = 16916|||Since u hv 2 matching rows in the POLine table against the row in the
POHeader table, u r getting 2 records. Try below query
select DISTINCT POheader.ponbr from POheader inner join POline on
POheader.Ponbr = POline.Ponbr and POline.ponbr= 16916;
Rakesh
"s commar" wrote:

> I have 2 tables POheader and POline. I am running the following SQL
> statement but am getting 2 records where as I should only be getting one.
> Could someone please assist.
> s_commar@.hotmail.com
>
> select POheader.ponbr from POheader inner join POline on POheader.Ponbr =
> POline.Ponbr and POline.ponbr
> = 16916;
>
> I should just be getting one record but I get 2 records. Could someone
> advise as to what I am doing wrong.
> Thanks
> s_commar@.hotmail.com
>
>

Assistance developing Query

Good Day;

I would appreciate assistance developing a query that I haven't been
able to develop without using a second table. I wish to count the
number of records that are still open on the first of each month.
Each record has an open date and a close date or the close date is
null i.e., the record is not yet closed. I've previously beaten this
by building a table, simply a list of the dates for the first of each
month for the next ten years or so, and then selecting values based
upon a date selected from that table. However I'd be happier if I
could do it without the second table. I'd be prepared to accept the
Min(Date) for each month as being the first of the month.

I've included some DDL statements to build and populate the table if
that helps. Since the selection is rather small and all the open
dates are very close together I think the result will be simply a
decreasing count from the month the first record is opened till today.

A pseudo code select statement might look like

Select Min(DateOpened) As DateOfInterest, Count(*) as [Qty Still Open]
FROM DetailT
Where DateReceived > DateOfInterest or DateReceived is Null and
DateOpened < DateOfInterest
Group by Min(DateOpened)
Order by Min(DateOpened)

I hope I've explained it sufficiently well.

CREATE TABLE [dbo].[DetailT] (
[Autonum] [int] IDENTITY (1, 1) NOT NULL ,
[QDNumber] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[DateOpened] [smalldatetime] NOT NULL ,
[DateReceived] [smalldatetime] NULL ,

)
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('C15788', '06/04/2005 9:35', 07/04/2005)
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('B16091', '06/04/2005 9:36', '07/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('B15001', '06/04/2005 9:51', '08/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('M18696', '06/04/2005 9:56', '06/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('C14969', '06/04/2005 10:05', '10/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('O10091', '06/04/2005 10:08', '12/04/2005')
Insert into DetailT (QDNumber, DateOpened)
VALUES('D01197', '06/04/2005 10:13')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('H15001', '06/04/2005 10:15', '08/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('J15090', '06/04/2005 10:24', '08/04/2005')
Insert into DetailT (QDNumber, DateOpened)
VALUES('J01202', '06/04/2005 10:31')
Insert into DetailT (QDNumber, DateOpened)
VALUES('G01193', '06/04/2005 10:32')
Insert into DetailT (QDNumber, DateOpened)
VALUES('K01164', '06/04/2005 10:35')
Insert into DetailT (QDNumber, DateOpened)
VALUES('K01162', '06/04/2005 10:48')
Insert into DetailT (QDNumber, DateOpened)
VALUES('F01124', '06/04/2005 10:59')
Insert into DetailT (QDNumber, DateOpened)
VALUES('H01147', '06/04/2005 11:01')
Insert into DetailT (QDNumber, DateOpened)
VALUES('S15068', '06/04/2005 11:10')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('E12322', '06/04/2005 11:32', '07/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('A12205', '06/04/2005 11:37', '06/04/2005')
Insert into DetailT (QDNumber, DateOpened, DateReceived)
VALUES('D12259', '06/04/2005 11:40', '07/04/2005')
Insert into DetailT (QDNumber, DateOpened)
VALUES('C03394', '06/04/2005 11:51')

If you made it this far thank you for your patience. Any help would be
appreciated.

Thank you.

BillBill wrote:

> Good Day;
> I would appreciate assistance developing a query that I haven't been
> able to develop without using a second table. I wish to count the
> number of records that are still open on the first of each month.
> Each record has an open date and a close date or the close date is
> null i.e., the record is not yet closed. I've previously beaten this
> by building a table, simply a list of the dates for the first of each
> month for the next ten years or so, and then selecting values based
> upon a date selected from that table. However I'd be happier if I
> could do it without the second table. I'd be prepared to accept the
> Min(Date) for each month as being the first of the month.
> I've included some DDL statements to build and populate the table if
> that helps. Since the selection is rather small and all the open
> dates are very close together I think the result will be simply a
> decreasing count from the month the first record is opened till today.
> A pseudo code select statement might look like
> Select Min(DateOpened) As DateOfInterest, Count(*) as [Qty Still Open]
> FROM DetailT
> Where DateReceived > DateOfInterest or DateReceived is Null and
> DateOpened < DateOfInterest
> Group by Min(DateOpened)
> Order by Min(DateOpened)
> I hope I've explained it sufficiently well.
> CREATE TABLE [dbo].[DetailT] (
> [Autonum] [int] IDENTITY (1, 1) NOT NULL ,
> [QDNumber] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [DateOpened] [smalldatetime] NOT NULL ,
> [DateReceived] [smalldatetime] NULL ,
> )
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('C15788', '06/04/2005 9:35', 07/04/2005)
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('B16091', '06/04/2005 9:36', '07/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('B15001', '06/04/2005 9:51', '08/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('M18696', '06/04/2005 9:56', '06/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('C14969', '06/04/2005 10:05', '10/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('O10091', '06/04/2005 10:08', '12/04/2005')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('D01197', '06/04/2005 10:13')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('H15001', '06/04/2005 10:15', '08/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('J15090', '06/04/2005 10:24', '08/04/2005')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('J01202', '06/04/2005 10:31')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('G01193', '06/04/2005 10:32')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('K01164', '06/04/2005 10:35')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('K01162', '06/04/2005 10:48')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('F01124', '06/04/2005 10:59')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('H01147', '06/04/2005 11:01')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('S15068', '06/04/2005 11:10')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('E12322', '06/04/2005 11:32', '07/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('A12205', '06/04/2005 11:37', '06/04/2005')
> Insert into DetailT (QDNumber, DateOpened, DateReceived)
> VALUES('D12259', '06/04/2005 11:40', '07/04/2005')
> Insert into DetailT (QDNumber, DateOpened)
> VALUES('C03394', '06/04/2005 11:51')
> If you made it this far thank you for your patience. Any help would be
> appreciated.
> Thank you.
> Bill

Where the SQL statement you would use to load the table?
Put parentheses around it.
Go from there.
There may be far more elegant solutions but your the one getting
the paycheck. ;-)
--
Daniel A. Morgan
University of Washington
damorgan@.x.washington.edu
(replace 'x' with 'u' to respond)|||On 18 Apr 2005 16:36:38 -0700, Bill wrote:

>I would appreciate assistance developing a query that I haven't been
>able to develop without using a second table.
(snip)
>I've previously beaten this
>by building a table, simply a list of the dates for the first of each
>month for the next ten years or so, and then selecting values based
>upon a date selected from that table. However I'd be happier if I
>could do it without the second table.

Hi Bill,

Why do you want to do it wothout a second table? Having a permanent
auxiliary calendar table in your database is actually quite useful and I
think that no database should ever be without one.
Here's a link to an article that shows how to create a general
all-purpose calendar table, how to fill it with data and several
examples of how to use it: http://www.aspfaq.com/show.asp?id=2519.

And here's how I'd write your query, using the table described above:

SELECT c.dt,
COUNT(*) as "Qty Still Open"
FROM Calendar AS c
INNER JOIN DetailT
ON ( DateReceived > c.dt OR DateReceived IS NULL )
AND DateOpened < c.dt
WHERE c.D = 1
AND c.dt BETWEEN (SELECT MIN(DateOpened)
FROM DetailT)
AND DATEADD(month, 1, (SELECT MAX(DateReceived)
FROM DetailT))
GROUP BY c.dt
ORDER BY c.dt

This one cuts off the listing at the lowest number. If you increase the
number (1) in the DATEADD expression, you can see that the number of
open cases remains constant after the last month listed.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||DA Morgan <damorgan@.x.washington.edu> wrote in message news:<1113891730.819997@.yasure>...
> Bill wrote:
> > Good Day;
> > I would appreciate assistance developing a query that I haven't been
> > able to develop without using a second table.

> > Thank you.
> > Bill
> Where the SQL statement you would use to load the table?
> Put parentheses around it.
> Go from there.
> There may be far more elegant solutions but your the one getting
> the paycheck. ;-)

Dan;

I'm sorry but I don't understand what you're trying to tell me. If
your first question is "Where is the SQL statement you would use to
load the table?" I don't have one, the data base is interactively
updated through an ASP based HTML form over the web. I did go to the
work of providing insert statements to assist anyone who might try to
help.

I don't understand what putting parentheses around it would do?

I hope there is a more elegant solution but unfortuantely I haven't
figured it out and was simply asking for assistance. If you don't
wish to help thats ok with me. Yes, I'm getting paid for the work I
do, but developing this solution is not what I was trained or educated
to do an so I'm learning as I go. I appologize if I've bothered you
by asking for help.

I will continue to explore the solution.

Cheers;

Bill|||Hugo Kornelis <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message news:<8oqa61p4rgmhtcfh7rgsc8dup9pj1a9d1t@.4ax.com>...
> On 18 Apr 2005 16:36:38 -0700, Bill wrote:
> >I would appreciate assistance developing a query that I haven't been
> >able to develop without using a second table.
> (snip)
> >I've previously beaten this
> >by building a table, simply a list of the dates for the first of each
> >month for the next ten years or so, and then selecting values based
> >upon a date selected from that table. However I'd be happier if I
> >could do it without the second table.
> Hi Bill,
> Why do you want to do it wothout a second table? Having a permanent
> auxiliary calendar table in your database is actually quite useful and I
> think that no database should ever be without one.
...
> This one cuts off the listing at the lowest number. If you increase the
> number (1) in the DATEADD expression, you can see that the number of
> open cases remains constant after the last month listed.
> Best, Hugo

Hugo;

Thank you for your assistance. I've reviewed the article you pointed
me to and have spent my spare time today building a number table and a
date table. I was reluctant to duplicate my earlier date table, which
only contained the dates for the first of the month into the SQL
Server environment since I felt that it was both cheating and
confusing. However the article showed that this can be a very useful
table and since it's been published I don't feel too bad about
emulating someone's work who know more about application development
than I do.

I do have one question, based mainly on my lack of formal training in
SQL Server and my experience this morning building the calendar table.
I was copying the code from the article and pasting it into SQL Query
Analyzer and running it, as I'm not certain where or how this code
should be executed. Most things ran very quickly after I modified
them properly to meet my environment. However the adding of row's to
the Calendar table (4,096) took several hours (2-3) I was really
surprised by this and wondered if I was doing something wrong but
since it finished successfully and subsequent code samples executed
quickly I moved on. My question is am I using the right part of the
SQL Server environment for this sort of work?

Thank you once again for your time and your assistance. Now that I've
overcome my reluctance to using the calendar table I'm comfortable
enough to go on and using you sample query to get what I was looking
for.

Thank you.

Cheers;

Bill|||On 20 Apr 2005 16:06:36 -0700, Bill wrote:

(snip)
>the article showed that this can be a very useful
>table and since it's been published I don't feel too bad about
>emulating someone's work who know more about application development
>than I do.

Hi Bill,

You certainly should not feel bad about it - sharing the code is exactly
the reason why Aaron has published it on his site.

Copying work from others may be a sin in artistic creative work, but in
software development, it's a sin NOT to copy and adapt proven solutions.

(snip)
>Most things ran very quickly after I modified
>them properly to meet my environment. However the adding of row's to
>the Calendar table (4,096) took several hours (2-3) I was really
>surprised by this

And so am I. Okay, the server does have a bit of work to do when
populating the table, but under normal circumstances, I would not expect
it to run for so long! A couple of minutes, maybe. Not hours.

I'm not sure if you still care to investigate this (since you now have
the table, and it's a one-time job after all), but if you do, then could
you please post the exact code you used to create and popultae the
tables?

>My question is am I using the right part of the
>SQL Server environment for this sort of work?

Yes, Query Analyzer is exactly the tool to use for these jobs.

Best, Hugo
--

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

Assistance building a query...

I am trying to generate some datasets with some queries...

With a given series information, it should return PART_NOs that has STD
= 1 and a unique price at that particular 'START', and keeping the
'TYPE' in consideration...

DB examples below:

Main DB

IDPART_NOSERIESSTD
1A-1A1
2A-2A1
3A-3A1
4D-1D1
5D-2D0

Price DB

IDPART_IDTYPESTARTPRICE
501X100050
511X1000040
521Y100060
531Y1000050
542X100050
552X1000040
562Y100060
572Y1000050
582X100090

etc.

main.ID and Price.PART_ID are paired together.

So in an example case, lets say I am querying for SERIES A, with TYPE
X. A table should be outputted something like

PART_NO
A-1100050
A-11000040
A-3100090

Note how it skipped printing A2 because the price is the same as A1.

I'm really looking for the SQL code here... I can't get it to filter on
distinct price.

SELECT MAIN.PART_NO, PRICING.START, PRICING.PRICE
FROM MAIN, PRICING
WHERE (MAIN.SERIES LIKE 'A')
AND (MAIN.STD = '1')
AND (PRICING.PRICE != '')
AND (PRICING.TYPE = 'X')
AND (MAIN.ID = PRICING.PART_ID)

I've been trying to use GROUP BY and HAVING to get what I need but it
doesn't seem to fit the bill. I guess I'm not terribly clear on how I
can use the SQL DISTINCT command...? If I try and use it in my WHERE
statement it gives me syntax errors, from what I understand you can
only have distinct in the select statement? I'm not sure how to
integrate that into the query to suit my needs.

Thanks for any help.A bit of clarification on my problem

If I just do a straight SQL distinct on my select statement, it does
what I want when you get down to it, but it completely destroys the
organization of the table. The part numbers were entered in a certain
manner and I do not believe they can be reorganized through any typical
sort. For example A-105A is higher then A-400B, but if you sorted in
Excel (for example) it would put 105 below 400

mazzarin@.gmail.com wrote:
> I am trying to generate some datasets with some queries...
> With a given series information, it should return PART_NOs that has STD
> = 1 and a unique price at that particular 'START', and keeping the
> 'TYPE' in consideration...
> DB examples below:
> Main DB
> IDPART_NOSERIESSTD
> 1A-1A1
> 2A-2A1
> 3A-3A1
> 4D-1D1
> 5D-2D0
> Price DB
> IDPART_IDTYPESTARTPRICE
> 501X100050
> 511X1000040
> 521Y100060
> 531Y1000050
> 542X100050
> 552X1000040
> 562Y100060
> 572Y1000050
> 582X100090
> etc.
> main.ID and Price.PART_ID are paired together.
>
> So in an example case, lets say I am querying for SERIES A, with TYPE
> X. A table should be outputted something like
> PART_NO
> A-1100050
> A-11000040
> A-3100090
> Note how it skipped printing A2 because the price is the same as A1.
>
> I'm really looking for the SQL code here... I can't get it to filter on
> distinct price.
> SELECT MAIN.PART_NO, PRICING.START, PRICING.PRICE
> FROM MAIN, PRICING
> WHERE (MAIN.SERIES LIKE 'A')
> AND (MAIN.STD = '1')
> AND (PRICING.PRICE != '')
> AND (PRICING.TYPE = 'X')
> AND (MAIN.ID = PRICING.PART_ID)
> I've been trying to use GROUP BY and HAVING to get what I need but it
> doesn't seem to fit the bill. I guess I'm not terribly clear on how I
> can use the SQL DISTINCT command...? If I try and use it in my WHERE
> statement it gives me syntax errors, from what I understand you can
> only have distinct in the select statement? I'm not sure how to
> integrate that into the query to suit my needs.
> Thanks for any help.|||Actually never mind, it doesn't do exactly what I want it to do... All
the prices are still duplicated, ideally I should only have at most 3
results being returned (according to the actual data being fed in)

I am beyond confused heh

I think I might have to do the filtering outside of SQL

mazzarin@.gmail.com wrote:
> A bit of clarification on my problem
> If I just do a straight SQL distinct on my select statement, it does
> what I want when you get down to it, but it completely destroys the
> organization of the table. The part numbers were entered in a certain
> manner and I do not believe they can be reorganized through any typical
> sort. For example A-105A is higher then A-400B, but if you sorted in
> Excel (for example) it would put 105 below 400
>
> mazzarin@.gmail.com wrote:
> > I am trying to generate some datasets with some queries...
> > With a given series information, it should return PART_NOs that has STD
> > = 1 and a unique price at that particular 'START', and keeping the
> > 'TYPE' in consideration...
> > DB examples below:
> > Main DB
> > IDPART_NOSERIESSTD
> > 1A-1A1
> > 2A-2A1
> > 3A-3A1
> > 4D-1D1
> > 5D-2D0
> > Price DB
> > IDPART_IDTYPESTARTPRICE
> > 501X100050
> > 511X1000040
> > 521Y100060
> > 531Y1000050
> > 542X100050
> > 552X1000040
> > 562Y100060
> > 572Y1000050
> > 582X100090
> > etc.
> > main.ID and Price.PART_ID are paired together.
> > So in an example case, lets say I am querying for SERIES A, with TYPE
> > X. A table should be outputted something like
> > PART_NO
> > A-1100050
> > A-11000040
> > A-3100090
> > Note how it skipped printing A2 because the price is the same as A1.
> > I'm really looking for the SQL code here... I can't get it to filter on
> > distinct price.
> > SELECT MAIN.PART_NO, PRICING.START, PRICING.PRICE
> > FROM MAIN, PRICING
> > WHERE (MAIN.SERIES LIKE 'A')
> > AND (MAIN.STD = '1')
> > AND (PRICING.PRICE != '')
> > AND (PRICING.TYPE = 'X')
> > AND (MAIN.ID = PRICING.PART_ID)
> > I've been trying to use GROUP BY and HAVING to get what I need but it
> > doesn't seem to fit the bill. I guess I'm not terribly clear on how I
> > can use the SQL DISTINCT command...? If I try and use it in my WHERE
> > statement it gives me syntax errors, from what I understand you can
> > only have distinct in the select statement? I'm not sure how to
> > integrate that into the query to suit my needs.
> > Thanks for any help.|||(mazzarin@.gmail.com) writes:
> I am trying to generate some datasets with some queries...
> With a given series information, it should return PART_NOs that has STD
>= 1 and a unique price at that particular 'START', and keeping the
> 'TYPE' in consideration...
> DB examples below:
> Main DB
> ID PART_NO SERIES STD
> 1 A-1 A 1
> 2 A-2 A 1
> 3 A-3 A 1
> 4 D-1 D 1
> 5 D-2 D 0
> Price DB
> ID PART_ID TYPE START PRICE
> 50 1 X 1000 50
> 51 1 X 10000 40
> 52 1 Y 1000 60
> 53 1 Y 10000 50
> 54 2 X 1000 50
> 55 2 X 10000 40
> 56 2 Y 1000 60
> 57 2 Y 10000 50
> 58 2 X 1000 90
> etc.
> main.ID and Price.PART_ID are paired together.
> So in an example case, lets say I am querying for SERIES A, with TYPE
> X. A table should be outputted something like
> PART_NO
> A-1 1000 50
> A-1 10000 40
> A-3 1000 90
> Note how it skipped printing A2 because the price is the same as A1.

But why does A-3 appear? Ir does not seem to appear in the Price DB
at all?

If there is an A-4 with the same values as A-1 would that be printed?

I'm sorry, but as you have presented the problem there are two many
unknowns. Furthermore, there is a standard recommendation that you include
in your post:

o CREATE TABLE statements for you table(s).
o INSERT statemetns with sample data.
o The desired result given the sample.

This makes it possible to easily copy and paste into Query Analyzer
to play around with the data and develop a tested solution.

--
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|||I actually ended up doing multiple queries, passing info between VBA
and SQL. Its not as nice of a solution but it works. Thank you for your
advice though. I will keep it in mind next time!

Erland Sommarskog wrote:
> (mazzarin@.gmail.com) writes:
> > I am trying to generate some datasets with some queries...
> > With a given series information, it should return PART_NOs that has STD
> >= 1 and a unique price at that particular 'START', and keeping the
> > 'TYPE' in consideration...
> > DB examples below:
> > Main DB
> > ID PART_NO SERIES STD
> > 1 A-1 A 1
> > 2 A-2 A 1
> > 3 A-3 A 1
> > 4 D-1 D 1
> > 5 D-2 D 0
> > Price DB
> > ID PART_ID TYPE START PRICE
> > 50 1 X 1000 50
> > 51 1 X 10000 40
> > 52 1 Y 1000 60
> > 53 1 Y 10000 50
> > 54 2 X 1000 50
> > 55 2 X 10000 40
> > 56 2 Y 1000 60
> > 57 2 Y 10000 50
> > 58 2 X 1000 90
> > etc.
> > main.ID and Price.PART_ID are paired together.
> > So in an example case, lets say I am querying for SERIES A, with TYPE
> > X. A table should be outputted something like
> > PART_NO
> > A-1 1000 50
> > A-1 10000 40
> > A-3 1000 90
> > Note how it skipped printing A2 because the price is the same as A1.
> But why does A-3 appear? Ir does not seem to appear in the Price DB
> at all?
> If there is an A-4 with the same values as A-1 would that be printed?
> I'm sorry, but as you have presented the problem there are two many
> unknowns. Furthermore, there is a standard recommendation that you include
> in your post:
> o CREATE TABLE statements for you table(s).
> o INSERT statemetns with sample data.
> o The desired result given the sample.
> This makes it possible to easily copy and paste into Query Analyzer
> to play around with the data and develop a tested solution.
>
> --
> 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

Sunday, March 11, 2012

Assigning the for xml query output to a variable

Hi,
I would like to generate an XML query using the 'for xml' clause and assign
that to a text variable for further manipulation.
for e.g., I would like to do some thing like this.
declare @.test text
Set @.test = Select * from test_table for xml auto
But this gives my the syntax error. Can anyone help capturing the xml output
of a query into a variable?
Regards,
ArunHi
Have you looked at the text datatype limitations. You can not use a lot of
the T-SQL string manipulation functions against it, so you can't really do
much with it once you have it.
You can do a SELECT ... INTO ... to write it to a temporary table, then
select it into your @.test variable. I have not tried it, but is a
suggestion.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Arun" <kathir_arun@.hotmail.com> wrote in message
news:ePOh0u8QFHA.576@.TK2MSFTNGP15.phx.gbl...
> Hi,
> I would like to generate an XML query using the 'for xml' clause and
> assign
> that to a text variable for further manipulation.
> for e.g., I would like to do some thing like this.
> declare @.test text
> Set @.test = Select * from test_table for xml auto
> But this gives my the syntax error. Can anyone help capturing the xml
> output
> of a query into a variable?
> Regards,
> Arun
>

Assigning results of a select query to variables...

Hi,

I think I'm just braindead or simply thick...since this shouldn't be that hard, but I'm stumped right now.

So, I'm trying to retrieve from a table, with a sql stored procedure with the sql like
"select height, width, depth from products where id=@.idinput"

OK, so this part is easy, but if I wanted to say, return this to my code and assign height to a variable Ht, width to Wd and depth to Dp, how could I do that?

This is what I've got so far...

[code]
cmdSelect = New SqlCommand( "GetProd", connstr )
cmdSelect.CommandType = CommandType.StoredProcedure
dbcon.Open()

dbcon.Close()
[/code]

The main prob is just what to connect this record to in order to access the individual fields.

Thx :)Return it as a datereader, then:


Do while dbreader.read()

var1 = dbreader("field1")
var2 = dbreader("field2")...

Loop

You could also return the values as output parameters. This used to be the much faster way in ADO, but I've read that performance is about the same either way in ADO.net. If it matters that much, try both and test it.|||Thx man, that does just the job. :)

Assigning query output to a variable

I am running a query that will return 1 field from 1 row. What is the
syntax to assign that to a variable.
Samplecode:
Declare @.DataFilePath varchar(200)
Declare @.DBName varchar(200)
Set @.DBName = 'TestDB'
@.DataFilePath = select FileName From master.dbo.sysaltfiles WHERE name =
@.DBName
Thanks!
Ron@.DataFilePath = select MAX(FileName) From master.dbo.sysaltfiles WHERE name
=
@.DBName
Or MIN. Since you are getting one row, it does not do much, but it does
tell SQL Server that only one value is coming out of the select.
RLF
"RSH" <way_beyond_oops@.yahoo.com> wrote in message
news:Op0ca4p%23FHA.1032@.TK2MSFTNGP11.phx.gbl...
>I am running a query that will return 1 field from 1 row. What is the
>syntax to assign that to a variable.
> Samplecode:
> Declare @.DataFilePath varchar(200)
> Declare @.DBName varchar(200)
> Set @.DBName = 'TestDB'
> @.DataFilePath = select FileName From master.dbo.sysaltfiles WHERE name =
> @.DBName
>
>
> Thanks!
> Ron
>
>

Assigning Passwords to Connection Managers using Expressions

Hi Experts here,

Sorry if this query had been raised earlier. While In DTS Packages we retrieve connection details for all Connections in a Package from a table and then assign them to the following global Variables

gv_Source_User, gv_Source_Pwd, gv_Source_DataSource, gv_Source_InitialCatalog

Finally we reassign these variables to repective Connection Properties using Dynamic Properties Task. After Migrating to SSIS though we are able to assign almost all variables to Properties of Connection Managers via Expression except the Password which we donot find in the drop down list in order to assign gv_Source_Pwd.

Is there any work around to assign passwords dynamically?

Many Thanks

Subhash Subramanyam

Hi, Was also thinking if we can go about using script task to do the same ..

|||No, you can't use script. You can assemble the complete connection string (with password) in an expression-based variable and then assign that to the ConnectionString property through an expression on the connection manager.

See www.connectionstrings.com if you need help building the string.
|||

Many Thanks to JayH.

I already had this in my mind yesterday with a bit of confusion - How to work out the code which uses Different connection Managers (what if it was Oracle). i.e. the Connection string built will be of different format .

A question for you is: Though the security can be compromised from Value set to ConnectionString, Why Password property hasn't been added in the dropdown list?

e.g. SQL OLEDB Connection, Data Source=Serverxyz;User ID=sa;Initial Catalog=PUBS_CATALOG;Provider=SQLOLEDB;Persist Security Info=True;

For Oracle, First Manually provide all the details, so that ConnectionString will be built on Connection Manager Properties. This seems really a burden that we must manually verify every derived connectionstring if it can successfully connect.

Many Thanks once again

Subhash Subramanyam

Thursday, March 8, 2012

Assigning data from an SQL query to a variable

Hello all,

for a project I am trying to implement PayPal processing for orders

public void CheckOut(Object s, EventArgs e)
{

String cartBusiness ="0413086@.chester.ac.uk";
String cartProduct;
int cartQuantity = 1;
Decimal cartCost;
int itemNumber = 1;

SqlConnection objConn3;
SqlCommand objCmd3;
SqlDataReader objRdr3;

objConn3 =new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
objCmd3 =new SqlCommand("SELECT * FROM catalogue WHERE ID=" + Request.QueryString["id"], objConn3);
objConn3.Open();
objRdr3 = objCmd3.ExecuteReader();
cartProduct ="Cheese";
cartCost = 1;
objRdr3.Close();
objConn3.Close();

cartBusiness = Server.UrlEncode(cartBusiness);

String strPayPal ="https://www.paypal.com/cgi-bin/webscr?cmd=_cart&upload=1&business=" + cartBusiness;

strPayPal += "&item_name_" + itemNumber + "=" + cartProduct;
strPayPal += "&item_number_" + itemNumber + "=" + cartQuantity;
strPayPal += "&amount_" + itemNumber + "=" + Decimal.Round(cartCost);

Response.Redirect(strPayPal);

Here is my current code. I have manually selected cartProduct = "Cheese" and cartCost = 1, however I would like these variables to be site by data from the query.

So I want cartProduct = Title and cartCost = Price from the SQL query.

How do I do this?

Thanks

DO NOT use string concatenation like you have now. Use Parameterized Queries.

you close the SQL connection not the reader first. Then loop through the reader, get the values and assign the variables. I would definetely recommend using Try/Catch block to catch any errors.

The following code is for illustration only.

objConn3 =new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
objCmd3 =new SqlCommand("SELECT * FROM catalogue WHERE ID=" + Request.QueryString["id"], objConn3);

Try
If objConn3.State = 0 Then objConn3.Open()

objRdr3 = objCmd3.ExecuteReader();

If DataReader.HasRows Then
Do While objRdr3 .Read()
cartProduct = objRdr3 .Item("cartProduct"))
cartCost = objRdr3 .Item("cartCost"))
Loop

End If
Catch exc As Exception
Response.Write(exc)
Finally

objRdr3.close()
If objConn3.State = ConnectionState.Open Then
objConn3.Close()
End If
End Try

Assigning a lower priority to some users in SQL Server.

I have a production database used by a web site, and at the same time a group of read-only users who can query the database directly “without the web site”

When one of the users runs a complex query, it slows down the server, and affects the web site.

Is it possible to change the SQL User account or SQL User Group’s priority to low?

You know, the same like in the Task Manager and Windows, I can change a process to low, so it will not affect the important processes, can I do this in SQL Server, and is there any workaround.

in my humble opinion

its the query that needs to be changed

or if your using 2005 you can implement HA feature

such as database snapshot, mirroring etc.

|||Besides the guessing, does anyone have a real solution? Are there sql execution priorities available in SQL Server? Or they are just in the deal databases, like Oracle?|||

if you are so convince that thats the best query you can write and there is no

room for improvement then you can schedule your heavy process to run

on offpeak times.

if that heavy process cross the line of tolerable performance your only option

is to kill that process.

the solution to your problem are

1. send readonly report users to a database snapshot if you are using 2k5

2. schedule the process to run on offpeak times

3. use page caching, fragment caching and most importanctly database caching in asp.net or on your website so you dont rely much on your database

By the way, what does this complex query do? if you would not mind.

how complex is it?

Assigning 1-row & multi-column query result to local variable

Hello,
I am just new to T-SQL programming on SQL server 2000. I would like to
ask you if it is possible (like in VBA for example) to save the result
of query (1 row, but multi columns) to some "array" or "object"
variable in order to reference the concrete components (fields) of
this variable in the future code.
For example in VBA:
Dim query1 as Recordset
Set query1 = CurrentDb.OpenRecordset("ABC")
MsgBox query1!ID
MsgBox query1!Comment
Or is the only way to save the results to the temp table and use other
queries to select the required fields? This means more rows of code
and slowing of the whole calculation process.
Thank you very much for your answer.
MilanMilan,
What are you trying to accomplish?
AMB
"Milan" wrote:

> Hello,
> I am just new to T-SQL programming on SQL server 2000. I would like to
> ask you if it is possible (like in VBA for example) to save the result
> of query (1 row, but multi columns) to some "array" or "object"
> variable in order to reference the concrete components (fields) of
> this variable in the future code.
> For example in VBA:
> Dim query1 as Recordset
> Set query1 = CurrentDb.OpenRecordset("ABC")
> MsgBox query1!ID
> MsgBox query1!Comment
>
> Or is the only way to save the results to the temp table and use other
> queries to select the required fields? This means more rows of code
> and slowing of the whole calculation process.
> Thank you very much for your answer.
> Milan
>|||No arrays in SQL but you could do something like this:
select @.var1 = col1, @.var2 = col2 ... from tableName where IDcol = ...
The query must return just 1 row though for this to work. If I remember
correctly, if it returns more then 1 row, then the variables will receive
the values of the last row.
Maybe if you described what you are trying to do, then someone could find a
better solution.
"Milan" <milan_vaclavik@.centrum.cz> wrote in message
news:b4cdce36.0503090705.1f5d824e@.posting.google.com...
> Hello,
> I am just new to T-SQL programming on SQL server 2000. I would like to
> ask you if it is possible (like in VBA for example) to save the result
> of query (1 row, but multi columns) to some "array" or "object"
> variable in order to reference the concrete components (fields) of
> this variable in the future code.
> For example in VBA:
> Dim query1 as Recordset
> Set query1 = CurrentDb.OpenRecordset("ABC")
> MsgBox query1!ID
> MsgBox query1!Comment
>
> Or is the only way to save the results to the temp table and use other
> queries to select the required fields? This means more rows of code
> and slowing of the whole calculation process.
> Thank you very much for your answer.
> Milan|||SQL is a declarative language not a procedural one like VB. Storing
values from rows to variables is something you should generally try to
avoid. Instead of retrieving values and then referencing them in future
code, aim to write declarative, set-based code that operates on the
whole set of data at once. Your SQL code will be much cleaner, more
efficient and more maintainable that way. Don't try to use TSQL like it
was VB.
It is in fact possible to assign column values to variables, using a
SET or SELECT statement but variable assignment should be the exception
rather than the rule. Frequent use of variable assignment from tables
implies that you'll be using cursor based processing - a common error
made by programmers new to SQL. If you have an actual problem (the code
you posted already doesn't do anything useful that can't be achieved
with a SELECT statement) then please come back with more information so
that we can suggest an alternative.
David Portas
SQL Server MVP
--|||I would like to thank you for your replies.
I have the table with columns named like "A_01", "A_02", ..., "A_30",
"B_01", "B_02", ..., "B_30", "C_01" etc. I know it is badly designed but
I inherited it from my colleague. I have created a complex (and slow)
query which returns 1 row from this table. What I have to do now
(separately for A, B, C...) is to insert some calculated values (based
on concrete values of 01, 02,..., 30) to some other tables. For example
if A_01 = 6, I have to input A_02/6 to the A_03th, (A_03+1)th, ...,
(A_03+5)th column of some concrete table. The calculation is really very
complex.
In VBA this is a trivial task but i can not manage it easily in T-SQL.
Thank you for your ideas!
Milan
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!|||Hello Milan,
If it's easy for you to do in VBA, then why not do it in VBA? What requirem
ent
is there that you must do this in T-SQL?
Craig

> I would like to thank you for your replies.
> I have the table with columns named like "A_01", "A_02", ..., "A_30",
> "B_01", "B_02", ..., "B_30", "C_01" etc. I know it is badly designed
> but I inherited it from my colleague. I have created a complex (and
> slow) query which returns 1 row from this table. What I have to do now
> (separately for A, B, C...) is to insert some calculated values (based
> on concrete values of 01, 02,..., 30) to some other tables. For
> example if A_01 = 6, I have to input A_02/6 to the A_03th, (A_03+1)th,
> ..., (A_03+5)th column of some concrete table. The calculation is
> really very complex.
> In VBA this is a trivial task but i can not manage it easily in T-SQL.
> Thank you for your ideas!
> Milan
> *** Sent via Developersdex http://www.examnotes.net *** Don't just
> participate in USENET...get rewarded for it!
>|||I think you've realised that the root of your problem is the poor
design. I'm not sure why you would perpetuate this by creating another
table rather than do it in a view or query but anyway you may be able
to use something like this:
INSERT INTO Garbage_Out (a_01, a_o2, a_03)
SELECT I.a_01, NULL, I.a_02/I.a_01,
CASE I.a_01
WHEN 1 THEN I.a_0?
WHEN 2 THEN I.a_0?
..
END,
CASE I.a_01
WHEN 1 THEN I.a_0?
WHEN 2 THEN I.a_0?
..
END
FROM Garbage_In AS I
Fill in the question marks yourself - I wasn't clear from your
narrative which columns you would want to refer to. This "design" is
probably beyond redemption. Tables are not arrays.
David Portas
SQL Server MVP
--|||Hello Milan,

> In VBA this is a trivial task but i can not manage it easily in T-SQL.
Why not do it in VBA, then? What requirement is there that you do it in
T-SQL?
Craig

assign variable to an XML query's result

Can I set output of an XML query to a variable (SQL Server 2000)? The
following query does not parse:
DECLARE @.Xml NTEXT
SET @.Xml =
(SELECT D.*
FROM WSDMS..Documents D
WHERE D.ID = @.DocumentID
FOR XML AUTO)
It's not possible for sql2k.
-oj
<bbla32@.op.pl> wrote in message
news:1172081331.938350.4510@.l53g2000cwa.googlegrou ps.com...
> Can I set output of an XML query to a variable (SQL Server 2000)? The
> following query does not parse:
> DECLARE @.Xml NTEXT
> SET @.Xml =
> (SELECT D.*
> FROM WSDMS..Documents D
> WHERE D.ID = @.DocumentID
> FOR XML AUTO)
>

assign variable to an XML query's result

Can I set output of an XML query to a variable (SQL Server 2000)? The
following query does not parse:
DECLARE @.Xml NTEXT
SET @.Xml = (SELECT D.*
FROM WSDMS..Documents D
WHERE D.ID = @.DocumentID
FOR XML AUTO)It's not possible for sql2k.
--
-oj
<bbla32@.op.pl> wrote in message
news:1172081331.938350.4510@.l53g2000cwa.googlegroups.com...
> Can I set output of an XML query to a variable (SQL Server 2000)? The
> following query does not parse:
> DECLARE @.Xml NTEXT
> SET @.Xml => (SELECT D.*
> FROM WSDMS..Documents D
> WHERE D.ID = @.DocumentID
> FOR XML AUTO)
>