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

Friday, March 30, 2012

Question transport-level error

Hi all,

I'm having a little problem with my sqlserver 2005.

I'm trying to crate a user in Microsoft SQL Server Management Studio throug a query.

Like this:
-
USE [master]
GO
CREATE LOGIN [MYUSER] WITH PASSWORD=N'MYPASSWORD', DEFAULT_DATABASE=[MYDB],
DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
ALTER LOGIN [MYUSER] ENABLE
GO

USE [msdb]
GO
CREATE USER [MYUSER] FOR LOGIN [MYUSER];
GO
GRANT EXECUTE ON [sp_start_job] TO [MYUSER]
GO
EXEC sp_addrolemember 'db_datareader', 'MYUSER'
GO
EXEC sp_addrolemember 'db_datawriter', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentOperatorRole', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentUserRole', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentReaderRole', 'MYUSER'
GO

Use [MYDB]
GO
CREATE USER [MYUSER] FOR LOGIN [MYUSER]
GO
EXEC sp_addrolemember 'db_datareader', 'MYUSER'
GO
EXEC sp_addrolemember 'db_datawriter', 'MYUSER'
GO

And drops the user by executing following:

Use [MYDB]
GO
EXEC sp_dropuser 'MYUSER'
GO

USE [msdb]
GO
REVOKE EXECUTE ON [sp_start_job] TO [MYUSER]
GO
EXEC sp_droprolemember 'SQLAgentOperatorRole', 'MYUSER'
GO
EXEC sp_droprolemember 'SQLAgentUserRole', 'MYUSER'
GO
EXEC sp_droprolemember 'SQLAgentReaderRole', 'MYUSER'
GO
EXEC sp_dropuser 'MYUSER'
GO

USE [master]
IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'MYUSER')
DROP LOGIN [MYUSER]

-Then if I from a query, first creates the user, then drops the user, I can't create him again? I get's the following error when trying:
Msg 10054, Level 20, State 0, Line 0
A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

I'f i then runs the createscript again, the user is created correctly.

Is there a way to avoid this foced lockout? Or how do i "refreash" my connection, without dataloss?

Best Regards
Henrik

Have you tried executing your scripts from sqlcmd instead of Management Studio? Are you seeing the same behavior?

Thanks
Laurentiu

|||

Hi Cristofor,

Thanks for you reply. I'v just tried that and get following:

HResult 0x2, Level 16, State 1
Named Pipes Provider: Could not open a connection to SQL Server [2].
Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establi
shing a connection to the server. When connecting to SQL Server 2005, this failu
re may be caused by the fact that under the default settings SQL Server does not
allow remote connections..
Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired.

But under "Server Properties" - "Connections"

The "Allow Remote connections to this server" is checked, with a query timeout on 600

|||

In some SQL Server SKUs the remote connection is disabled by default. Use SQL Server Configuration Manager to enable TCP/IP (or named pipes) on your SQL Server instance (requires to restart SQL Server service). Also make sure the Windows firewall is configured to allow SQL Server to accept connections.

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi Raul,

I have just enabled this it was disabled, but still im getting the same error.

But by executeing the script localy from the database server, it works fine. And can do it as many times as i please, whithout errors.
like this:

sqlcmd -sMYDBSERVER -E -i "C:\drop.sql"
And
sqlcmd -sMYDBSERVER -E -i "C:\Create.sql"

But it still drops the connection to the user elsewhere, on the first time it's used after creation.
Eg. First i drop the user, then i create it again with the scripts. Then i open a browser and goes to my website, wich uses this user to connect to the database to retrive and update information. Then the first time i try to login i get the error below. Then i push "F5" to refreash the page and all works fine again?

Soucre:

.Net SqlClient Data Provider

Error Message:

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

|||

My only guess is that your web application is somehow caching/reusing the old connection (with the old login), and when you refresh the page it reestablishes the connection. Remember that when you drop and create a login it is a whole new principal, not the same one (even if the name and password is the same), and any established connection will be invalidated and the connection will be forcedly terminated by the server the next time any application tries to use it.

I would recommend using SQL profiler to trace back new/closed connections as well as existing sessions to try to detect if this is indeed the case.

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi,

Thats also what im comming to. I haven't tryed the SQL profiler yet, but will do this later.

But i have found out that it's not enough only to stop and start the web site again on IIS. I have to restart the hole "IIS" to make the "refreash". So im thinking that the session is not terminated correctly from the website, when closing the browser/session?.

|||

Besides your investigation on why (and if) the web application is reusing the connection instead of reconnecting, I have one question for you: are you dropping and recreating this user in order to create a whole new principal (i.e. a new SID, with no existing objects, etc.), or just as a mechanism to prevent this principal from establishing a new connection?

If you are using these scripts to prevent new connections, you may also want to consider disabling the login instead. By disabling the login, you prevent new connections without affecting existing ones, and without the need to cleanup any objects or references (i.e. users) this principal may have in the system. You can find the syntax for this operation in ALTER LOGIN (http://msdn2.microsoft.com/en-us/library/ms189828.aspx).

-Raul Garcia

SDE/T

SQL Server Engine

|||

Actually im useing thise scripts as a part of my deploymentkit. This is to ensure that all securitysettings to any databases, stored procedures etc are droped. So i afterwards can replace them with either the same or new ones, without leaving anything behind.

But i took the change and implemented it into my deployment. The first time i got the same error about the "transport-level error". But that was because i've missed another scipt later in the installation, it was some inserts-stament i tried to execute from a vb SqlConnection. Then i moved those two things around, so it was the last code and then it worked fine, i can now open my webpage without the "transport-level error" :) yeah .. even after installing, uninstalling, installing ....

So i have to go back to the websession-closing, in my case, because under the "Activity Monitor" in sql, i can see a connection long after closing the browser. So this is now another problem for me, to find a way to kill this one.

But im stil interested in fixing the other problem, because it's annoying that things has to come in the correct order.. And the differens between executing it from a sql-query (in sql 2005), from command promt and from my msi-package. -Wich by the way executes it by calling a shell in vb wich runs a .cmd-file containing the two sql-scripts.

sqlcmd -sMYDBSERVER -E -i "C:\drop.sql" -o "C:\DropDBUser.log"
sqlcmd -sMYDBSERVER -E -i "C:\Create.sql" -o "C:\CreateDBUser.log"

But for the moment im happy :)

|||

I’m glad to hear that. Feel free to let us know if you have further security questions in SQL Server, we are always looking forward to help our customers whenever we have a chance.

-Raul Garcia

SDE/T

SQL Server Engine

Question transport-level error

Hi all,

I'm having a little problem with my sqlserver 2005.

I'm trying to crate a user in Microsoft SQL Server Management Studio throug a query.

Like this:
-
USE [master]
GO
CREATE LOGIN [MYUSER] WITH PASSWORD=N'MYPASSWORD', DEFAULT_DATABASE=[MYDB],
DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
ALTER LOGIN [MYUSER] ENABLE
GO

USE [msdb]
GO
CREATE USER [MYUSER] FOR LOGIN [MYUSER];
GO
GRANT EXECUTE ON [sp_start_job] TO [MYUSER]
GO
EXEC sp_addrolemember 'db_datareader', 'MYUSER'
GO
EXEC sp_addrolemember 'db_datawriter', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentOperatorRole', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentUserRole', 'MYUSER'
GO
EXEC sp_addrolemember 'SQLAgentReaderRole', 'MYUSER'
GO

Use [MYDB]
GO
CREATE USER [MYUSER] FOR LOGIN [MYUSER]
GO
EXEC sp_addrolemember 'db_datareader', 'MYUSER'
GO
EXEC sp_addrolemember 'db_datawriter', 'MYUSER'
GO

And drops the user by executing following:

Use [MYDB]
GO
EXEC sp_dropuser 'MYUSER'
GO

USE [msdb]
GO
REVOKE EXECUTE ON [sp_start_job] TO [MYUSER]
GO
EXEC sp_droprolemember 'SQLAgentOperatorRole', 'MYUSER'
GO
EXEC sp_droprolemember 'SQLAgentUserRole', 'MYUSER'
GO
EXEC sp_droprolemember 'SQLAgentReaderRole', 'MYUSER'
GO
EXEC sp_dropuser 'MYUSER'
GO

USE [master]
IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'MYUSER')
DROP LOGIN [MYUSER]

-Then if I from a query, first creates the user, then drops the user, I can't create him again? I get's the following error when trying:
Msg 10054, Level 20, State 0, Line 0
A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

I'f i then runs the createscript again, the user is created correctly.

Is there a way to avoid this foced lockout? Or how do i "refreash" my connection, without dataloss?

Best Regards
Henrik

Have you tried executing your scripts from sqlcmd instead of Management Studio? Are you seeing the same behavior?

Thanks
Laurentiu

|||

Hi Cristofor,

Thanks for you reply. I'v just tried that and get following:

HResult 0x2, Level 16, State 1
Named Pipes Provider: Could not open a connection to SQL Server [2].
Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establi
shing a connection to the server. When connecting to SQL Server 2005, this failu
re may be caused by the fact that under the default settings SQL Server does not
allow remote connections..
Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired.

But under "Server Properties" - "Connections"

The "Allow Remote connections to this server" is checked, with a query timeout on 600

|||

In some SQL Server SKUs the remote connection is disabled by default. Use SQL Server Configuration Manager to enable TCP/IP (or named pipes) on your SQL Server instance (requires to restart SQL Server service). Also make sure the Windows firewall is configured to allow SQL Server to accept connections.

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi Raul,

I have just enabled this it was disabled, but still im getting the same error.

But by executeing the script localy from the database server, it works fine. And can do it as many times as i please, whithout errors.
like this:

sqlcmd -sMYDBSERVER -E -i "C:\drop.sql"
And
sqlcmd -sMYDBSERVER -E -i "C:\Create.sql"

But it still drops the connection to the user elsewhere, on the first time it's used after creation.
Eg. First i drop the user, then i create it again with the scripts. Then i open a browser and goes to my website, wich uses this user to connect to the database to retrive and update information. Then the first time i try to login i get the error below. Then i push "F5" to refreash the page and all works fine again?

Soucre:

.Net SqlClient Data Provider

Error Message:

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

|||

My only guess is that your web application is somehow caching/reusing the old connection (with the old login), and when you refresh the page it reestablishes the connection. Remember that when you drop and create a login it is a whole new principal, not the same one (even if the name and password is the same), and any established connection will be invalidated and the connection will be forcedly terminated by the server the next time any application tries to use it.

I would recommend using SQL profiler to trace back new/closed connections as well as existing sessions to try to detect if this is indeed the case.

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi,

Thats also what im comming to. I haven't tryed the SQL profiler yet, but will do this later.

But i have found out that it's not enough only to stop and start the web site again on IIS. I have to restart the hole "IIS" to make the "refreash". So im thinking that the session is not terminated correctly from the website, when closing the browser/session?.

|||

Besides your investigation on why (and if) the web application is reusing the connection instead of reconnecting, I have one question for you: are you dropping and recreating this user in order to create a whole new principal (i.e. a new SID, with no existing objects, etc.), or just as a mechanism to prevent this principal from establishing a new connection?

If you are using these scripts to prevent new connections, you may also want to consider disabling the login instead. By disabling the login, you prevent new connections without affecting existing ones, and without the need to cleanup any objects or references (i.e. users) this principal may have in the system. You can find the syntax for this operation in ALTER LOGIN (http://msdn2.microsoft.com/en-us/library/ms189828.aspx).

-Raul Garcia

SDE/T

SQL Server Engine

|||

Actually im useing thise scripts as a part of my deploymentkit. This is to ensure that all securitysettings to any databases, stored procedures etc are droped. So i afterwards can replace them with either the same or new ones, without leaving anything behind.

But i took the change and implemented it into my deployment. The first time i got the same error about the "transport-level error". But that was because i've missed another scipt later in the installation, it was some inserts-stament i tried to execute from a vb SqlConnection. Then i moved those two things around, so it was the last code and then it worked fine, i can now open my webpage without the "transport-level error" :) yeah .. even after installing, uninstalling, installing ....

So i have to go back to the websession-closing, in my case, because under the "Activity Monitor" in sql, i can see a connection long after closing the browser. So this is now another problem for me, to find a way to kill this one.

But im stil interested in fixing the other problem, because it's annoying that things has to come in the correct order.. And the differens between executing it from a sql-query (in sql 2005), from command promt and from my msi-package. -Wich by the way executes it by calling a shell in vb wich runs a .cmd-file containing the two sql-scripts.

sqlcmd -sMYDBSERVER -E -i "C:\drop.sql" -o "C:\DropDBUser.log"
sqlcmd -sMYDBSERVER -E -i "C:\Create.sql" -o "C:\CreateDBUser.log"

But for the moment im happy :)

|||

I’m glad to hear that. Feel free to let us know if you have further security questions in SQL Server, we are always looking forward to help our customers whenever we have a chance.

-Raul Garcia

SDE/T

SQL Server Engine

sql

Question -sub query

I’m needing help with a query here. I have a table with an ID and Date which are my PK’s.

I believe this will take a sub query. I want several fields pulled (one per ID). It would be the one with the max(date)

Here is what I have so far (yes I know it doesn’t work but you should get the idea).

select myID, myDate, field1, field2, field3, field4

FROM

(select myID,max(myDate)

from myTable1

WHERE

DATALENGTH(field1)> 0OR

DATALENGTH(field2)> 0OR

DATALENGTH(field3)> 0OR

DATALENGTH(field4)> 0

groupby myID)

By the way the sub query here works on it’s own and gives me the records I want, I just need the other fields pulled in there

Here you are:

SELECT t1.myID, t1.myDateMax, t2.field1, t2.field2, t2.field3, t2.field4FROM

(SELECT myID,max(myDate)AS myDateMax

FROM myTable1WHERE field1ISNOTNULLOR field2ISNOTNULLOR field3ISNOTNULLOR field4ISNOTNULL

GROUPBY myID)AS t1INNERJOIN myTable1AS t2ON t1.myID=t2.myIDAND t1.myDateMax=t2.myDate

|||

Beautiful!!

Thank you Limno

sql

Wednesday, March 28, 2012

Question regarding Object querying

Platform - SQL Svr 2000 SP3a
I have a couple of questions regarding stored procs
1. Is there a way to query on keyword text withiin stored proceduers?
for example, if I wanted to find all stored proc's that contain 'AND
where col_name <> 3' in the statement(s), can I do that? Does Full-text
support only include Table objects?
2.) Do objects (specifically stored procedures) have a modified date
property that can be queried on? If so, how is this done?
Thanks,
-Troy> 1. Is there a way to query on keyword text withiin stored proceduers?
> for example, if I wanted to find all stored proc's that contain 'A
ND
> where col_name <> 3' in the statement(s), can I do that? Does Full-text
> support only include Table objects?
How do I find a stored procedure containing <text>?
http://www.aspfaq.com/show.asp?id=2037

> 2.) Do objects (specifically stored procedures) have a modified date
> property that can be queried on? If so, how is this done?
No. SQL Server does not save this information.
AMB
"Troy Jerkins" wrote:

> Platform - SQL Svr 2000 SP3a
> I have a couple of questions regarding stored procs
> 1. Is there a way to query on keyword text withiin stored proceduers?
> for example, if I wanted to find all stored proc's that contain 'A
ND
> where col_name <> 3' in the statement(s), can I do that? Does Full-text
> support only include Table objects?
> 2.) Do objects (specifically stored procedures) have a modified date
> property that can be queried on? If so, how is this done?
>
> Thanks,
> -Troy
>
>|||Thanks for the link. This very good.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:D9E8C74E-19CA-4549-905B-F1364E59E726@.microsoft.com...
> How do I find a stored procedure containing <text>?
> http://www.aspfaq.com/show.asp?id=2037
>
> No. SQL Server does not save this information.
>
> AMB
> "Troy Jerkins" wrote:
>

Monday, March 26, 2012

Question regarding creating If Else functions in my report

Hi, I'm new and i'm having trouble trying to create this query at the "DATA" tab of my rdl.

What i'm trying to do here is passing 2 employee name from two drop

down text box(doing a filtering with "From Employee" and "To

Employee"), and assign it to a global variable which i declared.

Is there something i miss out or i did worng which cause a error

"Incorrect syntax near the keyword 'BEGIN'. (.Net SqlClient Data

Provider)".

It would be so helpful of you if links of website or previous post or

any reference are provided, which give some basic tutorial on how to

create codes as shown below.

Thanks in advance

DECLARE @.G_StartEmp AS CHAR(10), @.G_EndEmp AS CHAR(10)


IF @.StartEmp > @.EndEmp

BEGIN

Set @.G_StartEmp = @.EndEmp

Set @.G_EndEmp = @.StartEmp

END

ELSE

BEGIN

Set @.G_StartEmp = @.StartEmp

Set @.G_EndEmp = @.EndEmp

END IF


BEGIN

select * from EMPLOYEE

where employeename between G_StartEmp and G_EndEmp

END

DId you wrap that code in a stored procedure ?

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de|||Hi, after spending some time again on this, i realize i added an extra "IF" , which is the cause of this error.

Thanks for taking your time to reply me Jens K. Suessmeyer.

DECLARE @.G_StartEmp AS CHAR(10), @.G_EndEmp AS CHAR(10)


IF @.StartEmp > @.EndEmp

BEGIN

Set @.G_StartEmp = @.EndEmp

Set @.G_EndEmp = @.StartEmp

END

ELSE

BEGIN

Set @.G_StartEmp = @.StartEmp

Set @.G_EndEmp = @.EndEmp

END (Originally was "END IF")


BEGIN

select * from EMPLOYEE

where employeename between G_StartEmp and G_EndEmp

END

question regarding CASE and GROUP BY

I have the below query and I am not sure if this will return an accurate aggregate, I know I cannot just group by my alias GLG_DELEGATE_ID, is this the way to handle aggregates when you have a CASE in the SELECT statement?

SELECT CASE
WHEN C.GLG_DELEGATE_ID IS null THEN C.GLG_ID
ELSE C.GLG_DELEGATE_ID
END AS GLG_DELEGATE_ID
,COUNT(P.CONSULTATION_ID) ACTIVITY_AMOUNT
FROM
dbo.CONSULTATION C
GROUP BY
C.GLG_DELEGATE_ID
, C.GLG_IDNo, just repeat your CASE code in the WHERE clause:

SELECT CASE WHEN C.GLG_DELEGATE_ID IS null THEN C.GLG_ID
ELSE C.GLG_DELEGATE_ID
END AS GLG_DELEGATE_ID
,COUNT(P.CONSULTATION_ID) ACTIVITY_AMOUNT
FROM dbo.CONSULTATION C
GROUP BY CASE WHEN C.GLG_DELEGATE_ID IS null THEN C.GLG_ID
ELSE C.GLG_DELEGATE_ID END
,C.GLG_ID

question regarding bcp

Hi ,
I am executing the following command from query analyzer. It is
successfull but i couldnot see the output file. I am connecting to the
database server from my workstation through query analyzer.
exec master..xp_cmdshell 'bcp "SELECT * FROM pubs..authors ORDER BY
au_lname" queryout C:\authors.txt -U sa -P xyz -c'
Here is the output,
NULL
Starting copy...
NULL
23 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.): total 16 Avg 0 (1437.50 rows per sec.)
The problem is i dont know where the output file is. Will it be in the
database server?. If so, then how can i save the output file in my
workstation.
Thanks in advance,
Vel.If you run BCP on the server it can only output to a location that it
can access from the server. Either output to a shared folder that can
be seen by both you and SQL's service account OR run BCP locally on
your workstation (from the command line).
David Portas
SQL Server MVP
--|||The command is executed on the server. If you want the file to be created on
the client, you need to
specify that, use an UNC drive for the client. the service account for SQL S
erver need permissions
for the share. I have a feeling that this isn't the best way to achieve this
, though. What about
having your client application create the file? Or what about executing BCP
on the client computer
instead of through xp_cmdshell on the server?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"velmj" <velmj@.discussions.microsoft.com> wrote in message
news:A3FC958F-EC28-494F-AFDA-70497218DD69@.microsoft.com...
> Hi ,
> I am executing the following command from query analyzer. It is
> successfull but i couldnot see the output file. I am connecting to the
> database server from my workstation through query analyzer.
>
> exec master..xp_cmdshell 'bcp "SELECT * FROM pubs..authors ORDER BY
> au_lname" queryout C:\authors.txt -U sa -P xyz -c'
> Here is the output,
> NULL
> Starting copy...
> NULL
> 23 rows copied.
> Network packet size (bytes): 4096
> Clock Time (ms.): total 16 Avg 0 (1437.50 rows per sec.)
> The problem is i dont know where the output file is. Will it be in the
> database server?. If so, then how can i save the output file in my
> workstation.
> Thanks in advance,
> Vel.|||The file should be in the root drive of the server where you saved it.
You might want to save it somewhere to a less "critial" folder than the
root drive. You can copy it across the network once you are done. Or you
can use the command-line BCP program right from your client and have the
final file automatically saved locally.
David Gugick
Imceda Software
www.imceda.com

Question regarding a Sql Query

Hello,

i have this query:
declare @.SubCompanyCode VARCHAR(6)
declare @.ProgramCode VARCHAR(10)
declare @.AttendeeTypeOption INT
DECLARE @.AttendeeTypeOptionOP CHAR(2)

set @.SubCompanyCode= 'A011'
set @.ProgramCode = 'ACL52B'
set @.AttendeeTypeOption= ''

If (@.AttendeeTypeOption<>'') SELECT @.AttendeeTypeOptionOP = 'EQ' ELSE SELECT @.AttendeeTypeOptionOP = ''

SELECT

M.City AS MeetingCity,
M.State AS MeetingState,
CASE
WHEN MA.AttendeeType = 1 THEN 'Participants'
WHEN MA.AttendeeType = 2 THEN 'Speaker/Faculty'

END AS AttendeeType,
Count(A.AttendeeID) as NoofRSVP
FROM
Programs P
INNER
JOIN eCDReservations M
ON P.SubCompanyCode = M.SubCompanyCode
AND P.ProgramCode = M.ProgramCode
left outer
JOIN MeetingAttendees MA
ON M.ReservationID = MA.MeetingID
left outer
JOIN Attendees A
ON MA.AttendeeID = A.AttendeeID
left outer
JOIN Regions R
ON MA.RegionCode = R.RegionCode
WHERE
P.SubCompanyCode = @.SubCompanyCode AND
P.ProgramCode = @.ProgramCode AND

CASE @.AttendeeTypeOptionOP
WHEN '' THEN 1
WHEN 'EQ' THEN
CASE

WHEN MA.AttendeeType = 1 THEN 1

ELSE 0
END
END=1
GROUP BY

M.City,
M.State,
MA.AttendeeType
ORDER BY
MA.AttendeeType

this query returns all 4 rows even though there is no matching meetingID in MeetingAttendees table. I have to modify this query (or write another query) in such a away that if I run it for "Participants" only means MA.AttendeeType = 1 (I will pass @.AttendeeTypeOption=1 for this case) then NoofRSVP should show #of participants and if MA.AttendeeType <> 1 then NoofRSVP should show 0 and AttendeeType will be empty (means it should ignore 'Speaker/Faculty').

Thanks for all your help...Your question is unclear, and there are some odd things in your code.

For instance, why are you left-joining the Regions table and then not referencing it anywhere?

And this clause in your WHERE statement: AND CASE @.AttendeeTypeOptionOP
WHEN '' THEN 1
WHEN 'EQ' THEN CASE
WHEN MA.AttendeeType = 1 THEN 1
ELSE 0
END
END = 1...could be written more simply like this: AND (@.AttendeeTypeOptionOP = ''
OR (@.AttendeeTypeOptionOP = 'EQ' AND MA.AttendeeType = 1))

Now, we don't know what you mean by "this query returns all 4 rows", because we don't know what you data looks like or how many records there are in each table. But since you are using an outer join on the MeetingAttendees table you can expect the query not to consider missing records in that table.

Friday, March 23, 2012

Question on the server trace in query analyzer

Hi,

When looking in the server trace in query analyzer – I can see how many ‘reads’ a stored procedure does.
So I'm wondering if we can determine whether our query is good or bad by looking at the number of reads/writes that showing in the Trace.

Thanks in advance

The CPU, Reads, and Writes values should display a low value if your queries are performing well. If they show high values, look at the text on which these values correspond to as this displays either the step or the query. Results in the server trace are asimilar to those that you have when you run SQL Profilersql

Wednesday, March 21, 2012

Question on SQL Server SQL

In DB2 one can issue a query like

db2 -x 'select tabname from syscat.tables'

and the output is cleaned up so all you get is/are the requested table
name(s)...no dotted lines...no column headings.

Does SQL Server have a similar construct?

Thanks
Gerryno dotted lines...no column headings.???

Check out the information_schema views in bol. Otherwise check out system tables also in bol. Without the version of SS you are using I can't be more specific.|||I think what you are looking for is bcp.exe

it's a console app for exporting data from SQL Server to a flat file.|||I think what you are looking for is bcp.exeAh! Now I get it.|||specifically:

bcp "select name from mydatabase.dbo.sysobjects where xtype='U'" queryout file.txt -c -T -SSERVERNAME|||Sorry about not posting the version.
Its SQL Server 2005.

Ok so it seems that SQL Server SQL does not have the -x construct and that the bcp.exe is needed.

Thanks

Question on SQL experission for complicated query

Hello All,

I have a problem on how to retrieve records from a database using SQL query. It is a little bit complicated query. I do not know what SQL query experission is correct.

In the database table, there are four fields "ClassID", "Personal Nmae", "Age", "Score". The following is an example for illustration.

Class Name Age Score
0 Bob 20 78 <====
0 John 26 66 <****
2 Wilson 28 88
1 John 26 77 <****
3 Alice 25 56
1 Bob 20 89 <====

In the above example table, I would like to know the scores of students who share the same name, at the same age, BUT in different class (ClassID is specified by the user). Actually, I need a SQL SELECT experission which will lead to a query result (a recordset) like the following

Bob 78 89
John 66 77select T.name
, T.score
from daTable as T
inner
join (
select name
, age
from daTable
group
by name
, age
having count(*) > 1
) as D
on D.name = T.name
and D.age = T.age|||r937,

Thank you for your reply, i will try your code and report latter.|||yes, it is correct. However, what is the SQL experission like if we use 'self join' to implement the same thing.|||Curiously is there anything wrong with doing the following?

SELECT s1.Name,s2.Score
FROM student_results s1
JOIN student_results s2
ON s1.Name=s2.Name
AND s1.Age=s2.Age
AND s1.Class<>s2.Class|||not "wrong" per se, but what if a given name has three scores -- what does your query return? what does mine?|||Thanks aschk abd r937,

Actually, in my application there are only two scores for a given name. One more further question,

If we have another table 'ClassTotalScore' consisting of two fields "Class" , "TotalScore"

Can I add some clause to the above suggested SQL experissions to get the sum of total scores of Class=0 and Class=2. Or I have to use another SQL statement to get the sum of total scores of two classes.

Moreover, if either way is possible, I would like to know whether ONE SQL statement is necessarilyfaster than TWO SQL statements.

Actually, those data in the two tables originally are stored in varibles in my VC++ 6.0 program. However, as more and more data are produced, the PC memory is almost exhaused. Hence, i have to resort to the database technology. I notice that the running speed of the databased based program is 10 times slower than the original program. I wonder if this is normal.|||Sounds like your database abstraction layer might be doing something odd (either that or your database system is setup badly/running slowly).
I would still recommend rudy's method of SQL Query by the way. I haven't tested mine with more than two results (because i deleted the tables) but from experience I know that rudy tends to be right ;)|||Unless your programme is using some really nasty inefficient way of storing all your SQL results?|||aschk,

thanks.

I think i did not express my problem clearly in the previous posts. Actually, the speed of storing data (write) is ok for me. I am compliant with the speed of retrieving data (read data)-- more than 10 times slower than the memory based method.

aschk, are you sure this is not normal.

BY the way, there are 1200 plus records in the database.

10 times slower than the original program|||Is the database on the same machine as the program? Is your database cache limit really low? 1200 is nothing really. If you said 12 Million records then I would question it. If your database is on a seperate machine and the records are big then transferring all that data across a network might be your slowdown point. Where does your program take the longest?|||aschk,

thanks.

Yes, I did the tests (both reading--retrieving data and writing--storing data) in the same program on a DELL Optiplex GX620 (3Ghz CPU), 2G memory.

I am new to SQL server 2000, where is the setting for database cache?|||What else is your server doing? Because for it to write quicker than it reads is definitely odd. If you run the query directly in Query analyser how long does it take?|||write = 1 row

read = all 1200 rows

of course it will be slower :cool:

cy, what indexes have you crated?

Question on SP_MakeWebTask

I'm using SP_MakeWebTask it's working OK. The problem is that if a
particular query returns no records, the string that gets written from
the:
<%begindetail%>
<%insert_data_here%>
<<%enddetail%>
part of the template file is: "The specified statement did not generate
any data"
Is there a way to substitute this string with a different one?
Thanks,
JoeHi
Have you tried using a UNION that returns an default record if your original
query returned nothing?
John
"joef" wrote:

> I'm using SP_MakeWebTask it's working OK. The problem is that if a
> particular query returns no records, the string that gets written from
> the:
> <%begindetail%>
> <%insert_data_here%>
> <<%enddetail%>
> part of the template file is: "The specified statement did not generate
> any data"
> Is there a way to substitute this string with a different one?
> Thanks,
> Joe
>sql

Tuesday, March 20, 2012

Question on repeated query

I have to select a number of fields for a report. Name Address, city,
state zip, etc. from a list of customers.
I have to select 2000 records from each of 29 states.
Is there a way to do this without repeating and repeating the code in
QA, or by changing the state manually and running it each time?
I have to select 2000 customers from WV, 2000 from VA, 2000 from FL,
2000 from TX and so on.
It's more of just a random selection of customers, with no other
requirements other than the name & address are a good one (i.e. non-null
last name, good zip code, etc).
Any help appreciated.Try,
select
Name Address, city, state, zip
from
t1 as a
where
customerid in (
select top 2000 customerid
from t1 as b
where b.state = a.state
)
go
If you run this query again, do not expect to pull same result because I am
not using "order by" clause.
AMB
"Blasting Cap" wrote:

> I have to select a number of fields for a report. Name Address, city,
> state zip, etc. from a list of customers.
> I have to select 2000 records from each of 29 states.
> Is there a way to do this without repeating and repeating the code in
> QA, or by changing the state manually and running it each time?
> I have to select 2000 customers from WV, 2000 from VA, 2000 from FL,
> 2000 from TX and so on.
> It's more of just a random selection of customers, with no other
> requirements other than the name & address are a good one (i.e. non-null
> last name, good zip code, etc).
> Any help appreciated.
>

Question on refining query

I tried to search for google but i wasn't exactly how to phase it. My tables has a column "DATE", i am populating a listbox using a record set and the generic query "Select DATE From Table1". I want to display only the Uniqu dates, but that i mean if 08/31/04 shows up a 100 times I only want to show it once in that listbox. I have tried altering the values from the recordset and storing them in a collection and looking to see if they reappear but i keep getting errors. So I figured that there had to be an easier way of just redefining the orinal query just to get those dates and then populating the listbox because much more trivial.

any help would be appreciatedFigured it out, just had to add distinct into the query

thanks

Question on Querys

Ok in Replication for sql 2000,'

what happens when a query such as 'update tableA set a=1 where id=5' affects 1 row. What will happen when it does not affect any row.

Aaron

hi

1) with one row

in case of a merge replication => the updated Data replicated to the subscriber

in case of a transaction replication => the statement replicated and affects 1 rows on the subscriber again

2) with no row

in case of a merge replication => NOTHING

in case of a transaction replication => the statement replicated and affects 0 rows on the subscriber again

In Case of only one row, there is not big difference

in case of 100000 rows there is a big difference, because in case of merge replication, all of 100000 rows replicated step by step, in case of transaction replication, the statement will block the replication a long time, because the statement (not the result) will be replicate to the subscriber

bye

Thorsten Ueberschaer

question on query

Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
NeilYou didn't provide DDL. Here's an example from Northwind:
select
*
from
Customers c
left
join
Orders o on o.CustomerID = c.CustomerID
and o.OrderDate >= '19970101'
This shows all customers and any orders placed on or after 1 JAN 1997.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
Neil|||Hi,
Go for LEFT OUTER JOIN. refer books online
Thanks
Hari
SQL Server MVP
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
> Hi,
> I need a query which returns all rows from one table and rows from another
> table if they are present.
> I also need to restrict the right hand table to certain rows.
> When I do this on;y the matching ros from RHS show.
> How d I get all rows from LHS and only atching rows in RHS?
> Many thanks,
> Neil
>|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
Please read what you wrote. Does that sound like a spec that anyone
can use for programming? A vague question gets a vague answer -- look
up OUTER JOIN syntax in BOL.|||Sorry.
if I use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I get a list of all MediaIDs from TICList and can see if there are any
orders in tblDeliveryLine.
But I need to restrict my view of tblDeliveryLine to a certain order. When I
use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I no longer get the full list from the TICList.
NEIL|||On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:

>Sorry.
>if I use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I get a list of all MediaIDs from TICList and can see if there are any
>orders in tblDeliveryLine.
>But I need to restrict my view of tblDeliveryLine to a certain order. When
I
>use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I no longer get the full list from the TICList.
Hi Neil,
First, get rid of the TOP 100 PERCENT. This is just useless extra text
to make the query harder to read. Returning all rows is the default, so
you don't need to specify that you want all the rows. (And frankly, I'm
not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
clause, so you might even end up with a sub-optimal execution plan!).
The reason that your modification doesn't work, is that you filter on
the outer table in the where clause. This effectively changes the outer
join to an inner join. All rows from the first table without matching
rows from the second table get a set of NULLS as a result of the outer
join; since this NULL is never equal to 67, those rows are removed by
the WHERE filter. The solution is to move the filtering condition to the
JOIN condition.
Also, please start using table aliases instead of endlessly repeating
the same table name. Make them short and mnemonic for best effect.
Here's a version of your query that's not only corrected, but much
easier to read and maintain as well:
SELECT list.TICname, list.MediaID,
line.MediaID, line.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList AS list
LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
ON list.MediaID = line.MediaID
AND line.TICDeliveryHeadID = 67
ORDER BY list.TICname
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi Hugo,
I'm obliged for your help.
In fact I had already solved the problem with:
SELECT TICList.*, CurOrder.iOrder
FROM ngjarma_general.aycs_v_TICList TICList LEFT OUTER JOIN
(SELECT MediaID, iOrder
FROM ngjarma_general.aycs_tblTICDeliveryLine
WHERE (TICDeliveryHeadID = 67)) CurOrder ON TICList.MediaID =
CurOrder.MediaID
However, yours in much nicer and I'm changing my solution right now.
Thanks for the tips on shortening the code - I admit that I posted these
directly from EM, but I do usually tidy them up before using them in
Dreamweaver.
Once again, many thanks for the code and also the general tips.
NEIL
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:sj0q81puksr46e9l3qa2lqrqrjv0orkpi3@.
4ax.com...
> On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:
>
> Hi Neil,
> First, get rid of the TOP 100 PERCENT. This is just useless extra text
> to make the query harder to read. Returning all rows is the default, so
> you don't need to specify that you want all the rows. (And frankly, I'm
> not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
> clause, so you might even end up with a sub-optimal execution plan!).
> The reason that your modification doesn't work, is that you filter on
> the outer table in the where clause. This effectively changes the outer
> join to an inner join. All rows from the first table without matching
> rows from the second table get a set of NULLS as a result of the outer
> join; since this NULL is never equal to 67, those rows are removed by
> the WHERE filter. The solution is to move the filtering condition to the
> JOIN condition.
> Also, please start using table aliases instead of endlessly repeating
> the same table name. Make them short and mnemonic for best effect.
> Here's a version of your query that's not only corrected, but much
> easier to read and maintain as well:
> SELECT list.TICname, list.MediaID,
> line.MediaID, line.TICDeliveryHeadID
> FROM ngjarma_general.aycs_v_TICList AS list
> LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
> ON list.MediaID = line.MediaID
> AND line.TICDeliveryHeadID = 67
> ORDER BY list.TICname
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

question on query

Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
Neil
You didn't provide DDL. Here's an example from Northwind:
select
*
from
Customers c
left
join
Orders o on o.CustomerID = c.CustomerID
and o.OrderDate >= '19970101'
This shows all customers and any orders placed on or after 1 JAN 1997.
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
..
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
Neil
|||Hi,
Go for LEFT OUTER JOIN. refer books online
Thanks
Hari
SQL Server MVP
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
> Hi,
> I need a query which returns all rows from one table and rows from another
> table if they are present.
> I also need to restrict the right hand table to certain rows.
> When I do this on;y the matching ros from RHS show.
> How d I get all rows from LHS and only atching rows in RHS?
> Many thanks,
> Neil
>
|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
Please read what you wrote. Does that sound like a spec that anyone
can use for programming? A vague question gets a vague answer -- look
up OUTER JOIN syntax in BOL.
|||Sorry.
if I use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I get a list of all MediaIDs from TICList and can see if there are any
orders in tblDeliveryLine.
But I need to restrict my view of tblDeliveryLine to a certain order. When I
use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliver yHeadID
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDelive ryHeadID = 67)
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I no longer get the full list from the TICList.
NEIL
|||On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:

>Sorry.
>if I use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I get a list of all MediaIDs from TICList and can see if there are any
>orders in tblDeliveryLine.
>But I need to restrict my view of tblDeliveryLine to a certain order. When I
>use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliver yHeadID
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDelive ryHeadID = 67)
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I no longer get the full list from the TICList.
Hi Neil,
First, get rid of the TOP 100 PERCENT. This is just useless extra text
to make the query harder to read. Returning all rows is the default, so
you don't need to specify that you want all the rows. (And frankly, I'm
not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
clause, so you might even end up with a sub-optimal execution plan!).
The reason that your modification doesn't work, is that you filter on
the outer table in the where clause. This effectively changes the outer
join to an inner join. All rows from the first table without matching
rows from the second table get a set of NULLS as a result of the outer
join; since this NULL is never equal to 67, those rows are removed by
the WHERE filter. The solution is to move the filtering condition to the
JOIN condition.
Also, please start using table aliases instead of endlessly repeating
the same table name. Make them short and mnemonic for best effect.
Here's a version of your query that's not only corrected, but much
easier to read and maintain as well:
SELECT list.TICname, list.MediaID,
line.MediaID, line.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList AS list
LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
ON list.MediaID = line.MediaID
AND line.TICDeliveryHeadID = 67
ORDER BY list.TICname
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Hi Hugo,
I'm obliged for your help.
In fact I had already solved the problem with:
SELECT TICList.*, CurOrder.iOrder
FROM ngjarma_general.aycs_v_TICList TICList LEFT OUTER JOIN
(SELECT MediaID, iOrder
FROM ngjarma_general.aycs_tblTICDeliveryLine
WHERE (TICDeliveryHeadID = 67)) CurOrder ON TICList.MediaID =
CurOrder.MediaID
However, yours in much nicer and I'm changing my solution right now.
Thanks for the tips on shortening the code - I admit that I posted these
directly from EM, but I do usually tidy them up before using them in
Dreamweaver.
Once again, many thanks for the code and also the general tips.
NEIL
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:sj0q81puksr46e9l3qa2lqrqrjv0orkpi3@.4ax.com...
> On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:
>
> Hi Neil,
> First, get rid of the TOP 100 PERCENT. This is just useless extra text
> to make the query harder to read. Returning all rows is the default, so
> you don't need to specify that you want all the rows. (And frankly, I'm
> not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
> clause, so you might even end up with a sub-optimal execution plan!).
> The reason that your modification doesn't work, is that you filter on
> the outer table in the where clause. This effectively changes the outer
> join to an inner join. All rows from the first table without matching
> rows from the second table get a set of NULLS as a result of the outer
> join; since this NULL is never equal to 67, those rows are removed by
> the WHERE filter. The solution is to move the filtering condition to the
> JOIN condition.
> Also, please start using table aliases instead of endlessly repeating
> the same table name. Make them short and mnemonic for best effect.
> Here's a version of your query that's not only corrected, but much
> easier to read and maintain as well:
> SELECT list.TICname, list.MediaID,
> line.MediaID, line.TICDeliveryHeadID
> FROM ngjarma_general.aycs_v_TICList AS list
> LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
> ON list.MediaID = line.MediaID
> AND line.TICDeliveryHeadID = 67
> ORDER BY list.TICname
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

question on query

Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
NeilYou didn't provide DDL. Here's an example from Northwind:
select
*
from
Customers c
left
join
Orders o on o.CustomerID = c.CustomerID
and o.OrderDate >= '19970101'
This shows all customers and any orders placed on or after 1 JAN 1997.
--
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
Neil|||Hi,
Go for LEFT OUTER JOIN. refer books online
Thanks
Hari
SQL Server MVP
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
> Hi,
> I need a query which returns all rows from one table and rows from another
> table if they are present.
> I also need to restrict the right hand table to certain rows.
> When I do this on;y the matching ros from RHS show.
> How d I get all rows from LHS and only atching rows in RHS?
> Many thanks,
> Neil
>|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
Please read what you wrote. Does that sound like a spec that anyone
can use for programming? A vague question gets a vague answer -- look
up OUTER JOIN syntax in BOL.|||Sorry.
if I use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =ngjarma_general.aycs_tblTICDeliveryLine.MediaID
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I get a list of all MediaIDs from TICList and can see if there are any
orders in tblDeliveryLine.
But I need to restrict my view of tblDeliveryLine to a certain order. When I
use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =ngjarma_general.aycs_tblTICDeliveryLine.MediaID
WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I no longer get the full list from the TICList.
NEIL|||On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:
>Sorry.
>if I use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I get a list of all MediaIDs from TICList and can see if there are any
>orders in tblDeliveryLine.
>But I need to restrict my view of tblDeliveryLine to a certain order. When I
>use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I no longer get the full list from the TICList.
Hi Neil,
First, get rid of the TOP 100 PERCENT. This is just useless extra text
to make the query harder to read. Returning all rows is the default, so
you don't need to specify that you want all the rows. (And frankly, I'm
not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
clause, so you might even end up with a sub-optimal execution plan!).
The reason that your modification doesn't work, is that you filter on
the outer table in the where clause. This effectively changes the outer
join to an inner join. All rows from the first table without matching
rows from the second table get a set of NULLS as a result of the outer
join; since this NULL is never equal to 67, those rows are removed by
the WHERE filter. The solution is to move the filtering condition to the
JOIN condition.
Also, please start using table aliases instead of endlessly repeating
the same table name. Make them short and mnemonic for best effect.
Here's a version of your query that's not only corrected, but much
easier to read and maintain as well:
SELECT list.TICname, list.MediaID,
line.MediaID, line.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList AS list
LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
ON list.MediaID = line.MediaID
AND line.TICDeliveryHeadID = 67
ORDER BY list.TICname
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi Hugo,
I'm obliged for your help.
In fact I had already solved the problem with:
SELECT TICList.*, CurOrder.iOrder
FROM ngjarma_general.aycs_v_TICList TICList LEFT OUTER JOIN
(SELECT MediaID, iOrder
FROM ngjarma_general.aycs_tblTICDeliveryLine
WHERE (TICDeliveryHeadID = 67)) CurOrder ON TICList.MediaID =CurOrder.MediaID
However, yours in much nicer and I'm changing my solution right now.
Thanks for the tips on shortening the code - I admit that I posted these
directly from EM, but I do usually tidy them up before using them in
Dreamweaver.
Once again, many thanks for the code and also the general tips.
NEIL
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:sj0q81puksr46e9l3qa2lqrqrjv0orkpi3@.4ax.com...
> On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:
>>Sorry.
>>if I use
>>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>>ngjarma_general.aycs_v_TICList.MediaID,
>> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>>Expr1
>>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
>> ngjarma_general.aycs_tblTICDeliveryLine ON
>>ngjarma_general.aycs_v_TICList.MediaID =>>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>>I get a list of all MediaIDs from TICList and can see if there are any
>>orders in tblDeliveryLine.
>>But I need to restrict my view of tblDeliveryLine to a certain order. When
>>I
>>use
>>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>>ngjarma_general.aycs_v_TICList.MediaID,
>> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>>Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
>>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
>> ngjarma_general.aycs_tblTICDeliveryLine ON
>>ngjarma_general.aycs_v_TICList.MediaID =>>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>>WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
>>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>>I no longer get the full list from the TICList.
> Hi Neil,
> First, get rid of the TOP 100 PERCENT. This is just useless extra text
> to make the query harder to read. Returning all rows is the default, so
> you don't need to specify that you want all the rows. (And frankly, I'm
> not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
> clause, so you might even end up with a sub-optimal execution plan!).
> The reason that your modification doesn't work, is that you filter on
> the outer table in the where clause. This effectively changes the outer
> join to an inner join. All rows from the first table without matching
> rows from the second table get a set of NULLS as a result of the outer
> join; since this NULL is never equal to 67, those rows are removed by
> the WHERE filter. The solution is to move the filtering condition to the
> JOIN condition.
> Also, please start using table aliases instead of endlessly repeating
> the same table name. Make them short and mnemonic for best effect.
> Here's a version of your query that's not only corrected, but much
> easier to read and maintain as well:
> SELECT list.TICname, list.MediaID,
> line.MediaID, line.TICDeliveryHeadID
> FROM ngjarma_general.aycs_v_TICList AS list
> LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
> ON list.MediaID = line.MediaID
> AND line.TICDeliveryHeadID = 67
> ORDER BY list.TICname
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

question on query

Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
NeilYou didn't provide DDL. Here's an example from Northwind:
select
*
from
Customers c
left
join
Orders o on o.CustomerID = c.CustomerID
and o.OrderDate >= '19970101'
This shows all customers and any orders placed on or after 1 JAN 1997.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
Hi,
I need a query which returns all rows from one table and rows from another
table if they are present.
I also need to restrict the right hand table to certain rows.
When I do this on;y the matching ros from RHS show.
How d I get all rows from LHS and only atching rows in RHS?
Many thanks,
Neil|||Hi,
Go for LEFT OUTER JOIN. refer books online
Thanks
Hari
SQL Server MVP
"Neil Jarman" <neil@.tNOiSPAMvPLEASEy.co.uk> wrote in message
news:d6gdu1$bro$1$8300dec7@.news.demon.co.uk...
> Hi,
> I need a query which returns all rows from one table and rows from another
> table if they are present.
> I also need to restrict the right hand table to certain rows.
> When I do this on;y the matching ros from RHS show.
> How d I get all rows from LHS and only atching rows in RHS?
> Many thanks,
> Neil
>|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
Please read what you wrote. Does that sound like a spec that anyone
can use for programming? A vague question gets a vague answer -- look
up OUTER JOIN syntax in BOL.|||Sorry.
if I use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I get a list of all MediaIDs from TICList and can see if there are any
orders in tblDeliveryLine.
But I need to restrict my view of tblDeliveryLine to a certain order. When I
use
SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
ngjarma_general.aycs_v_TICList.MediaID,
ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
ngjarma_general.aycs_tblTICDeliveryLine ON
ngjarma_general.aycs_v_TICList.MediaID =
ngjarma_general.aycs_tblTICDeliveryLine.MediaID
WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
ORDER BY ngjarma_general.aycs_v_TICList.TICname
I no longer get the full list from the TICList.
NEIL|||On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:

>Sorry.
>if I use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I get a list of all MediaIDs from TICList and can see if there are any
>orders in tblDeliveryLine.
>But I need to restrict my view of tblDeliveryLine to a certain order. When
I
>use
>SELECT TOP 100 PERCENT ngjarma_general.aycs_v_TICList.TICname,
>ngjarma_general.aycs_v_TICList.MediaID,
> ngjarma_general.aycs_tblTICDeliveryLine.MediaID AS
>Expr1, ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID
>FROM ngjarma_general.aycs_v_TICList LEFT OUTER JOIN
> ngjarma_general.aycs_tblTICDeliveryLine ON
>ngjarma_general.aycs_v_TICList.MediaID =
>ngjarma_general.aycs_tblTICDeliveryLine.MediaID
>WHERE (ngjarma_general.aycs_tblTICDeliveryLine.TICDeliveryHeadID = 67)
>ORDER BY ngjarma_general.aycs_v_TICList.TICname
>I no longer get the full list from the TICList.
Hi Neil,
First, get rid of the TOP 100 PERCENT. This is just useless extra text
to make the query harder to read. Returning all rows is the default, so
you don't need to specify that you want all the rows. (And frankly, I'm
not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
clause, so you might even end up with a sub-optimal execution plan!).
The reason that your modification doesn't work, is that you filter on
the outer table in the where clause. This effectively changes the outer
join to an inner join. All rows from the first table without matching
rows from the second table get a set of NULLS as a result of the outer
join; since this NULL is never equal to 67, those rows are removed by
the WHERE filter. The solution is to move the filtering condition to the
JOIN condition.
Also, please start using table aliases instead of endlessly repeating
the same table name. Make them short and mnemonic for best effect.
Here's a version of your query that's not only corrected, but much
easier to read and maintain as well:
SELECT list.TICname, list.MediaID,
line.MediaID, line.TICDeliveryHeadID
FROM ngjarma_general.aycs_v_TICList AS list
LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
ON list.MediaID = line.MediaID
AND line.TICDeliveryHeadID = 67
ORDER BY list.TICname
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi Hugo,
I'm obliged for your help.
In fact I had already solved the problem with:
SELECT TICList.*, CurOrder.iOrder
FROM ngjarma_general.aycs_v_TICList TICList LEFT OUTER JOIN
(SELECT MediaID, iOrder
FROM ngjarma_general.aycs_tblTICDeliveryLine
WHERE (TICDeliveryHeadID = 67)) CurOrder ON TICList.MediaID =
CurOrder.MediaID
However, yours in much nicer and I'm changing my solution right now.
Thanks for the tips on shortening the code - I admit that I posted these
directly from EM, but I do usually tidy them up before using them in
Dreamweaver.
Once again, many thanks for the code and also the general tips.
NEIL
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:sj0q81puksr46e9l3qa2lqrqrjv0orkpi3@.
4ax.com...
> On Thu, 19 May 2005 08:01:17 +0100, Neil Jarman wrote:
>
> Hi Neil,
> First, get rid of the TOP 100 PERCENT. This is just useless extra text
> to make the query harder to read. Returning all rows is the default, so
> you don't need to specify that you want all the rows. (And frankly, I'm
> not sure if the optimizer is smart enough to ignore the TOP 100 PERCENT
> clause, so you might even end up with a sub-optimal execution plan!).
> The reason that your modification doesn't work, is that you filter on
> the outer table in the where clause. This effectively changes the outer
> join to an inner join. All rows from the first table without matching
> rows from the second table get a set of NULLS as a result of the outer
> join; since this NULL is never equal to 67, those rows are removed by
> the WHERE filter. The solution is to move the filtering condition to the
> JOIN condition.
> Also, please start using table aliases instead of endlessly repeating
> the same table name. Make them short and mnemonic for best effect.
> Here's a version of your query that's not only corrected, but much
> easier to read and maintain as well:
> SELECT list.TICname, list.MediaID,
> line.MediaID, line.TICDeliveryHeadID
> FROM ngjarma_general.aycs_v_TICList AS list
> LEFT OUTER JOIN ngjarma_general.aycs_tblTICDeliveryLine AS line
> ON list.MediaID = line.MediaID
> AND line.TICDeliveryHeadID = 67
> ORDER BY list.TICname
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

Monday, March 12, 2012

Question on Query

Hi, please help...

I have a table:

Brand | Profit | Loss

1 | 100 | 11
2 | 234 | 22
3 | 300 | 33
and want to get the result: Sum(Profit) where brand <= 2, Sum(Loss) where Brand = 3
The result should be look like:
Profit | Loss
334 | 33
Can you show me the sql query please? I am urgent need it for my work... please help..

I think this should work
Select (Select sum(Profit) From tableName Where brand<=2) As Profit,
(Select sum(Loss) From tableName Where brand=3) As Loss|||Many thanks, it works fine.
I don't know that the sql query can be just simply, thx for the help.|||One more question, is it possible i can sum up those 2 values?
so that the total will be:
Total
367|||

SELECT
Sum(Profit) as Total
WHERE
Brand <= 2
or
Brand = 3

|||

I think you have make a mistake. i want to get the result ofsum(profit) where brand <=2+ sum(loss) where brand = 3.
but not sum all the profit or loss
The result should be [(100)<- from brand 1 profit] + [(234)<- from brand 2 profit] + [(33)<- from brand 3 loss]

Total
367

|||

Try this

Select (Select sum(Profit) From tableName Where brand<=2) As Profit,
(Select sum(Loss) From tableName Where brand=3) As Loss,
((Select sum(Profit) From tableName Where brand<=2) + (Select sum(Loss) From tableName Where brand=3)) As Total