Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Wednesday, March 28, 2012

ROBUST PLAN error

Hi all
I'm trying to INSERT rows from one table to the other in a Oracle Linked server to SQL server
My query is something like this
INSERT INTO ORACLE_LINK..User.Table
SELECT *
FROM ORACLE_LINK..User.Table
I'm getting the following error
Server: Msg 510, Level 16, State 1, Line
Cannot create a worktable row larger than allowable maximum. Resubmit your query with the ROBUST PLAN hint
(Both are oracle tables only)
Can anybody tell the reason for this error
Thanks
Siva.It looks like the rows in the Oracle tables are longer than the maximum
rowlength in SQL Server, which is 8060 bytes.
You are probably best off to issue this query as a pass-through query using
OPENQUERY(ORACLE_LINK, 'INSERT INTO User.Table1SELECT * FROM User.Table2')
--
Jacco Schalkwijk
SQL Server MVP
"Siva" <siva116@.yahoo.com> wrote in message
news:0CD3DD0E-9B5A-441F-A040-030C9E108750@.microsoft.com...
> Hi all,
> I'm trying to INSERT rows from one table to the other in a Oracle Linked
server to SQL server.
> My query is something like this:
> INSERT INTO ORACLE_LINK..User.Table1
> SELECT *
> FROM ORACLE_LINK..User.Table2
> I'm getting the following error:
> Server: Msg 510, Level 16, State 1, Line 1
> Cannot create a worktable row larger than allowable maximum. Resubmit your
query with the ROBUST PLAN hint.
> (Both are oracle tables only).
> Can anybody tell the reason for this error?
> Thanks,
> Siva.

ROBUST PLAN error

Hi all,
I'm trying to INSERT rows from one table to the other in a Oracle Linked se
rver to SQL server.
My query is something like this:
INSERT INTO ORACLE_LINK..User.Table1
SELECT *
FROM ORACLE_LINK..User.Table2
I'm getting the following error:
Server: Msg 510, Level 16, State 1, Line 1
Cannot create a worktable row larger than allowable maximum. Resubmit your q
uery with the ROBUST PLAN hint.
(Both are oracle tables only).
Can anybody tell the reason for this error?
Thanks,
Siva.It looks like the rows in the Oracle tables are longer than the maximum
rowlength in SQL Server, which is 8060 bytes.
You are probably best off to issue this query as a pass-through query using
OPENQUERY(ORACLE_LINK, 'INSERT INTO User.Table1SELECT * FROM User.Table2')
Jacco Schalkwijk
SQL Server MVP
"Siva" <siva116@.yahoo.com> wrote in message
news:0CD3DD0E-9B5A-441F-A040-030C9E108750@.microsoft.com...
> Hi all,
> I'm trying to INSERT rows from one table to the other in a Oracle Linked
server to SQL server.
> My query is something like this:
> INSERT INTO ORACLE_LINK..User.Table1
> SELECT *
> FROM ORACLE_LINK..User.Table2
> I'm getting the following error:
> Server: Msg 510, Level 16, State 1, Line 1
> Cannot create a worktable row larger than allowable maximum. Resubmit your
query with the ROBUST PLAN hint.
> (Both are oracle tables only).
> Can anybody tell the reason for this error?
> Thanks,
> Siva.

Friday, March 23, 2012

Right single quotation mark errors

Hi,
I've created a table in SQL Server 2000 and I'm now trying to search
through the data and return specific rows. I'm using this command:

select * from Export where libelle_court='Recherche d'investisseurs'

The problem is this: The search fails whenever there is a curly
single quotation mark within the table field ( ' as opposed to ' ).

For example, if the field entry in my table is this:
Recherche d'investisseurs

then both of the following commands retun no fields:
select * from Export where libelle_court='Recherche d'investisseurs'
select * from Export where libelle_court='Recherche d''investisseurs'

However, if the field entry in my table is this:
Recherche d'investisseurs

then both of the commands quoted above succeed.

How can I get SQL Server to treat the curly quotation mark correctly
and return the right results? I've tried changing the collation but
with no success.

Thanks,

RobHi

In general if there is a quotation mark in the field it can be escaped with
another quotation mark, therefore I am not sure why the second example does
not work.

> select * from Export where libelle_court='Recherche d''investisseurs'

What does

select * from Export where libelle_court like 'Recherche d%'

return?

Also check out:

http://msdn.microsoft.com/library/d...con_03_7mch.asp

http://msdn.microsoft.com/library/d...earchvalues.asp

Collation will not effect this.

John

"Robert Garrett" <rgagarrett@.hotmail.com> wrote in message
news:b9c50dd6.0311030229.1ea4c288@.posting.google.c om...
> Hi,
> I've created a table in SQL Server 2000 and I'm now trying to search
> through the data and return specific rows. I'm using this command:
> select * from Export where libelle_court='Recherche d'investisseurs'
> The problem is this: The search fails whenever there is a curly
> single quotation mark within the table field ( ' as opposed to ' ).
> For example, if the field entry in my table is this:
> Recherche d'investisseurs
> then both of the following commands retun no fields:
> select * from Export where libelle_court='Recherche d'investisseurs'
> select * from Export where libelle_court='Recherche d''investisseurs'
> However, if the field entry in my table is this:
> Recherche d'investisseurs
> then both of the commands quoted above succeed.
> How can I get SQL Server to treat the curly quotation mark correctly
> and return the right results? I've tried changing the collation but
> with no success.
> Thanks,
> Rob|||Just another thought, depending on what the datatypes and options are, check
out trailing spaces. (Also see ANSI_PADDING in BOL)

John

"John Bell" <jbellnewsposts@.hotmail.com> wrote in message
news:bo5fp2$6q8$1@.sparta.btinternet.com...
> Hi
> In general if there is a quotation mark in the field it can be escaped
with
> another quotation mark, therefore I am not sure why the second example
does
> not work.
> > select * from Export where libelle_court='Recherche d''investisseurs'
> What does
> select * from Export where libelle_court like 'Recherche d%'
> return?
> Also check out:
>
http://msdn.microsoft.com/library/d...con_03_7mch.asp
>
http://msdn.microsoft.com/library/d...earchvalues.asp
> Collation will not effect this.
> John
> "Robert Garrett" <rgagarrett@.hotmail.com> wrote in message
> news:b9c50dd6.0311030229.1ea4c288@.posting.google.c om...
> > Hi,
> > I've created a table in SQL Server 2000 and I'm now trying to search
> > through the data and return specific rows. I'm using this command:
> > select * from Export where libelle_court='Recherche d'investisseurs'
> > The problem is this: The search fails whenever there is a curly
> > single quotation mark within the table field ( ' as opposed to ' ).
> > For example, if the field entry in my table is this:
> > Recherche d'investisseurs
> > then both of the following commands retun no fields:
> > select * from Export where libelle_court='Recherche d'investisseurs'
> > select * from Export where libelle_court='Recherche d''investisseurs'
> > However, if the field entry in my table is this:
> > Recherche d'investisseurs
> > then both of the commands quoted above succeed.
> > How can I get SQL Server to treat the curly quotation mark correctly
> > and return the right results? I've tried changing the collation but
> > with no success.
> > Thanks,
> > Rob|||Thanks for the help.

I'm not sure exactly what the problem was but it has gone now. I was
working on a number of things so I don't know quite what it was that
fixed the problem. I thought it might be because I was changing the
collation, but I cannot use this to repeat the fault. The web sites
were useful, though, so thanks again for the help.

Robsql

Right characters from ~

Hai,
Who can help me '
I'm making a query from a table.
In that table there is a column with the name NR_
The rows of that column give a result as
~2000252
~2003
~26578
What i want as result, the most right character from the ~character and as
result in the same column
200252
2003
26578
Who can help me ?There are several string related functions that will do what you want. Look
up documentation on right(), substring() and replace()
"Jaap" <Jaap@.discussions.microsoft.com> wrote in message
news:B0A0060F-EA08-4AE0-A516-67C4623564CA@.microsoft.com...
> Hai,
> Who can help me '
> I'm making a query from a table.
> In that table there is a column with the name NR_
> The rows of that column give a result as
> ~2000252
> ~2003
> ~26578
> What i want as result, the most right character from the ~character and as
> result in the same column
> 200252
> 2003
> 26578
> Who can help me ?|||Hi
Try something like:
SELECT RIGHT (col1,CHARINDEX('~',REVERSE(col1))-1)
FROM
( SELECT '~2000252' as col1
UNION ALL SELECT '~2003'
UNION ALL SELECT '~26578'
UNION ALL SELECT 'abc~def' ) A
John
"Jaap" <Jaap@.discussions.microsoft.com> wrote in message
news:B0A0060F-EA08-4AE0-A516-67C4623564CA@.microsoft.com...
> Hai,
> Who can help me '
> I'm making a query from a table.
> In that table there is a column with the name NR_
> The rows of that column give a result as
> ~2000252
> ~2003
> ~26578
> What i want as result, the most right character from the ~character and as
> result in the same column
> 200252
> 2003
> 26578
> Who can help me ?|||Hi,
Use the below query
select replace(column_name,'~','') as column from table_name
Thanks
Hari
SQL Server MVP
"Jaap" <Jaap@.discussions.microsoft.com> wrote in message
news:B0A0060F-EA08-4AE0-A516-67C4623564CA@.microsoft.com...
> Hai,
> Who can help me '
> I'm making a query from a table.
> In that table there is a column with the name NR_
> The rows of that column give a result as
> ~2000252
> ~2003
> ~26578
> What i want as result, the most right character from the ~character and as
> result in the same column
> 200252
> 2003
> 26578
> Who can help me ?|||yes, this is great it works
many thanks
"John Bell" wrote:

> Hi
> Try something like:
> SELECT RIGHT (col1,CHARINDEX('~',REVERSE(col1))-1)
> FROM
> ( SELECT '~2000252' as col1
> UNION ALL SELECT '~2003'
> UNION ALL SELECT '~26578'
> UNION ALL SELECT 'abc~def' ) A
> John
> "Jaap" <Jaap@.discussions.microsoft.com> wrote in message
> news:B0A0060F-EA08-4AE0-A516-67C4623564CA@.microsoft.com...
>
>sql

Friday, March 9, 2012

Returns 0 rows but which part of the where clause caused it.

I currently have a piece of SQL that will return a row if the input is
valid for the process. My application is a warehouse system. I need to
verify that the thing that is picked for the order can really be used
for that order. It is the correct product, it is in the correct status,
in the correct warehouse, ... Well up until now used one SQL statement
to achieve this. The row was returned or not. If not then the thing
being picked could not be used. Now my boss wants me to return why.
Essentially i will have to get the data and process this in code. Does
anyone have a SQL solution to this? Any tricks anyone uses to determine
which part(s) of the where clause (or join) caused the exclusion?
danWhat if more than 1 condition is FALSE?
There's lots of ways you could implement this, but sooner or later you'll
have to test each condition individually to find the cause.
You could test them up front and not run the query if an "error" condition
is found, or you could run the query and only test the conditions if
@.@.ROWCOUNT = 0.
You could indicate the reason by using RAISERROR, or maintain a table of
error codes and return them in the query, or you could ...
"Dan Holmes" wrote:

> I currently have a piece of SQL that will return a row if the input is
> valid for the process. My application is a warehouse system. I need to
> verify that the thing that is picked for the order can really be used
> for that order. It is the correct product, it is in the correct status,
> in the correct warehouse, ... Well up until now used one SQL statement
> to achieve this. The row was returned or not. If not then the thing
> being picked could not be used. Now my boss wants me to return why.
> Essentially i will have to get the data and process this in code. Does
> anyone have a SQL solution to this? Any tricks anyone uses to determine
> which part(s) of the where clause (or join) caused the exclusion?
> dan
>

Wednesday, March 7, 2012

Returning Value from Dynamic query

I want to get the count of rows in the table which match the status. I am writing dynamic query for it..
Create Procedure Dyn_Get_CountByStatus
(
@.TableName varchar(200),
@.Status int
)
as
Begin
Declare @.strQuery varchar(500)
Declare @.count int
set @.strQuery = 'select count(*) from '+@.TableName + 'where status=' + @.Status
set @.count =exec(@.strQuery)
return @.count
End
GO

This query is not working. How can get the desired result using dynamic query

Try using the @.@.rowcount instead....

Create Procedure Dyn_Get_CountByStatus
(
@.TableName varchar(200),
@.Status int
)
as
Begin
Declare @.strQuery varchar(500)
Declare @.count int
set @.strQuery = 'select * from '+@.TableName + 'where status=' + @.Status
exec(@.strQuery)

set @.count =@.@.rowcount
return @.count
End
GO

|||

You can do something like what I show below, BUT.... before you do, you should know that using dynamic SQL in the way you are using it is a VERY BAD IDEA. Suppose someone names a table something like [(select 1 i) T delete clients --] Then if you run this procedure, all rows from the table called [clients] will be deleted! If anyone has permission to create tables in your database on which this procedure will be executed, they can create a maliciously-named table name and wait for someone with elevated permission to run this procedure. You can protect yourself from most dangers fairly well by using QUOTENAME, though there are some truncation questions that can still allow security risks even when QUOTENAME is used. Valuable reading: http://www.sommarskog.se/dynamic_sql.html http://mvp.unixwiz.net/techtips/sql-injection.html -- MODIFY AT YOUR OWN RISK create table clients (i int) insert into clients values (10) insert into clients values (13) go declare @.tn sysname set @.tn = 'clients' declare @.TotalRecords int declare @.sql nvarchar(600) set @.sql = N' select @.TotalRecords = count(*) from '+ quotename(@.tn) + ' where i > @.param' exec sp_executesql @.sql, N'@.param int, @.TotalRecords int OUTPUT', @.TotalRecords = @.TotalRecords OUTPUT, @.param = 11 select @.TotalRecords go -- Steve Kass -- Drew University ashwin_k_s@.discussions.microsoft.com wrote:
> I want to get the count of rows in the table which match the status. I
> am writing dynamic query for it..
>
> Create Procedure Dyn_Get_CountByStatus
> (
> @.TableName varchar(200),
> @.Status int
> )
> as
> Begin
> Declare @.strQuery varchar(500)
> Declare @.count int
> set @.strQuery = 'select count(*) from '+@.TableName + 'where status='
> + @.Status
> set @.count =exec(@.strQuery)
> return @.count
> End
> GO
>
> This query is not working. How can get the desired result using dynamic
> query
>
>
>

returning the primary key of the last rows updated

I would like to return the the Primary Key of the row altered from this query - what changes do I need to make?
UPDATE Members SET LastLog = @.time WHERE UserName=@.user AND Password=@.pass;

Thanks in advance,
Is the primary key an IDENTITY value? If so then you could do this:
UPDATE Members SET LastLog = @.time WHERE UserName=@.user AND Password=@.pass;SELECT @.myPrimaryKey = SCOPE_IDENTITY()

|||I am trying to kill 2 birds with uno piedroSmile [:)] - I want thisreturn the Primary key ( which is the identity ) when someone islogging in and also update the last time they last logged in to thepresent.
My first quess was to do:
PDATE Members SET LastLog = @.time WHERE UserName=@.user AND Password=@.pass;SELECT SCOPE_IDENTITY()
But this keeps returning (NULL) - even though the row has been updated.
Thanks in advance

|||Can you post more of your code?
|||
Actually - this is what I was putting in my query analyzer-
UPDATE Members SET LastLog = @.time WHERE UserName=@.user AND Password=@.pass;
its ok -
I will just work with using this :
UPDATE Members SET LastLog = @.time WHERE UserName=@.user AND Password=@.pass; SELECT MemberID WHERE UserName=@.user AND Password=@.pass;
I will just dig around some more.


|||Oh gosh, I just realized that you are doing an UPDATE, not an INSERT! I don't know where my head was; I'm sorry.
In that case I would SELECT the MemeberID to be UPDATEd first into avariable, then perform the UPDATE with the WHERE condition being theMemberID you determined.

|||How about using an output parameter and assigning it SCOPE_IDENTITY or @.@.IDENTITY?
I'm not sure if @.@.IDENTITY only gets set to the ID of the latest INSERT or also UPDATE. It would be easy to try of course.

returning the number of rows from TOP PERCENT

Greetings.

I want to write a sql query that returns the number of rows from a query that uses top percent. For example,

select top (7) percent object from objecttable

It appears that @.@.rowcount will give the info but it does so as a separate column on each returned row.

Any suggestions would be appreciated.

Thanks.

alan

Try this

select top (7) percent object , count(1) over (partition by 1)

from objecttable order by somecolumn

You are using the new window aggregate ability.

Remember you should always use an order by with TOP

|||

Thanks for the quick reply.

I tried

select top (7) percent objectid , count(1) over (partition by 1)

from bases order by state

and got

(objectid) (no column name)

16 85
19 85
23 85
85 85
38 85
34 85

I'm not sure what '85' represents. When I select and use @.@.rowcount I get '6' in each row. All I really want to do is return '6'. I figure I missed something.

alan

|||@.@.ROWCOUNT gives the number of rows affected by the last statement. So when you use it in the SELECT list you are returning the rows that were affected by the statement before the SELECT. It is not the same as the rows that will be returned by the query. Best is to issue another query "SELECT @.@.ROWCOUNT as rows" after the query or count on the client-side. This will provide the best performance. You could use COUNT with OVER clause but note that has performance implications due to additional computation, sorting etc.|||

This will return the single value 6 (Given your table holds 85 rows)

WITH t1 AS
(SELECT TOP(7) PERCENT * FROM test)
SELECT COUNT(*) FROM t1;

Or this one:

SELECT COUNT(*)
FROM (SELECT TOP(7) PERCENT * FROM test) as t1;

The Execution Plan for Both Queries is the same.

|||Works great. Thanks !|||Works for me. Cool ! Thanks.|||

Or just

select count(1) *7/100

from mytable

|||

Sorry, but the result is not the same (Given the table test holds 85 rows):

SELECT COUNT(1) *7/100 FROM test;

Returns 5

SELECT COUNT(*)
FROM (SELECT TOP(7) PERCENT * FROM test) as t1;

Returns 6

To do it like your hint, the formula must be

SELECT CAST(ROUND(COUNT(1) * 7./100, 1) AS INT) FROM test;

Which returns 6.

There's no performance difference, but i'll prefer the solution which is the easiest to understand.

|||

The answers are different because the TOP will return whole rows i.e. rounds up.

So the answer is something like 5.3

Returning the newest rows

I have a query set up that returns the data that I would like, but I
would only like the latest data for each vehicle number. The query I
have set up is

SELECT TOP 100 PERCENT dbo.vwEvents.EventName,
dbo.luSessionAll.SessionName, dbo.luOuting.OutingNumber,
dbo.luVehicle.VehicleName, dbo.luOuting.OutingID,
dbo.tblOutings.OutingStartTime,dbo.tblSessions.Ses sionDate,dbo.tblSessions.SessionStartTime
FROM dbo.vwSessions INNER JOIN dbo.vwEvents ON
dbo.vwSessions.Event = dbo.vwEvents.EventID
INNER JOIN
dbo.luSessionAll ON dbo.vwEvents.EventID =
dbo.luSessionAll.Event INNER JOIN
dbo.luOuting ON dbo.luSessionAll.SessionID =
dbo.luOuting.SessionID INNER JOIN
dbo.luVehicle ON dbo.luSessionAll.Vehicle =
dbo.luVehicle.VehicleID INNER JOIN
dbo.tblOutings ON dbo.luOuting.OutingID =
dbo.tblOutings.OutingID INNER JOIN
dbo.tblSessions ON dbo.tblOutings.[Session] =
dbo.tblSessions.SessionID
GROUP BY dbo.vwEvents.EventName, dbo.luSessionAll.SessionName,
dbo.luOuting.OutingNumber, dbo.luVehicle.VehicleName,
dbo.luOuting.OutingID, dbo.tblOutings.OutingStartTime,
dbo.tblSessions.SessionStartTime, dbo.tblSessions.SessionDate
ORDER BY dbo.luVehicle.VehicleName, dbo.tblSessions.SessionDate,
dbo.tblSessions.SessionStartTime, dbo.tblOutings.OutingStartTime

this returns all the outings. I would like the outing that has, in
order of importance, the latest session date, latest session time and
latest outing start time. Outing start time can sometimes be <<Null>>
but the other two always have values. How would I go about doing this?
thanks in advance for any help(pltaylor3@.gmail.com) writes:
> I have a query set up that returns the data that I would like, but I
> would only like the latest data for each vehicle number. The query I
> have set up is
> SELECT TOP 100 PERCENT dbo.vwEvents.EventName,
>...
> ORDER BY dbo.luVehicle.VehicleName, dbo.tblSessions.SessionDate,
> dbo.tblSessions.SessionStartTime, dbo.tblOutings.OutingStartTime

I don't have the time to look into the problem as such, but I feel
obliged to point out that the above looks dubious.

TOP 100 PERCENT does not make any sense at all, that is just white noice,
so I suggest that you remove.

At this point, I am not surprised if you say that this in fact a view
definition, and you need the TOP 100 for the ORDER BY to be permitted.
Well, it is still white noise. In SQL 2000 a SELECT from the view is
very like to return rows in the order set up by the ORDER BY clause, but
that is just mere chance. In SQL 2005 this is far likely and more than one
has been bitten by this.

The only way to get an ordered result from a query is to include an ORDER
BY clause in the query itself. You cannot use views to encapsulate order.

--
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|||(pltaylor3@.gmail.com) writes:
> I have a query set up that returns the data that I would like, but I
> would only like the latest data for each vehicle number. The query I
> have set up is
>...
> this returns all the outings. I would like the outing that has, in
> order of importance, the latest session date, latest session time and
> latest outing start time. Outing start time can sometimes be <<Null>>
> but the other two always have values. How would I go about doing this?
> thanks in advance for any help

Without know what is what in the tables, I will have to guess a bit.
Maybe this is what you are looking for. And if it's not, maybe it's
enough to get you going:

SELECT E.EventName, SA.SessionName, O.OutingNumber,
V.VehicleName, O.OutingID, Os.OutingStartTime,
S.SessionDate,S.SessionStartTime
FROM dbo.vwSessions Ss
JOIN dbo.vwEvents E ON Ss.Event = E.EventID
JOIN dbo.luSessionAll SA ON E.EventID = SA.Event
JOIN dbo.luOuting O ON SA.SessionID = O.SessionID
JOIN dbo.luVehicle V ON SA.Vehicle = V.VehicleID
JOIN dbo.tblOutings Os ON O.OutingID =
(SELECT TOP 1 Os.OutingID
FROM dbo.tblOutings Os1
JOIN dbo.tblSesseions S1 ON
Os.[Session] = S.SessionID
ORDER BY S1.SessionDate DESC,
S1.SessionSessionStartTime DESC,
Os1.OutingStartTime DESC)
JOIN dbo.tblSessions S ON Os.[Session] = S.SessionID
ORDER BY V.VehicleName, S.SessionDate, S.SessionStartTime,
Os.OutingStartTime

I replaced the table/view names with alias to make the queries easier
to read.

I also did away with the GROUP BY that did not seem to serve any
purporse. Maybe it's a DISTINCT you need. Then again, if you need a
DISTINCT this is an indication that the query is lacking a condition
somewhere.

--
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

Saturday, February 25, 2012

Returning rows with NULL using WHERE statements

Hi All

I have only just started using SQL Server as part of a new job, and have come across something while using Select statements. When you do a query using the Where clause eg. Where city = 'London' it returns results for just London, if you then do the same but using Where city <> 'London' again the results are obvious, but records where the city field is NULL do not appear in either? I would have assumed them to appear as part of the second query...

As I said, this is probably a daft question but if anyone can shed some light on it, it'd be much appreciated.

take a look here http://sqlservercode.blogspot.com/2006/01/null-trouble-in-sql-server-land.html

you need to do Where city <> 'London' or city is null

because null compared to anything is unknown

even null compared to null is unknown take a look at this

declare @.i int,@.i2 int
select @.i ,@.i2
if @.i = @.i2
select 'yes'
else
select 'no'

assuming ansi nulls is on (which is the default and you should leave it like that)

if it is set to off you will get no as a result

SET ANSI_NULLS OFF
go
declare @.i int,@.i2 int
select @.i ,@.i2
if @.i = @.i2
select 'yes'
else
select 'no'
go

SET ANSI_NULLS ON

GO

Denis the SQL Menace

http://sqlservercode.blogspot.com/

|||That's great - thanks very much!

Returning rows as columns

Hi,
I have two tables ItemMaster and ItemCondition. One item can have multiple
conditions in the form of rows in ItemCondition. But while returning these,
I
would like to return it in the form of columns. Is that possible?
Below is the DDL of my table structure
CREATE TABLE [dbo].[ItemCondition] (
[ItemConditionId] [int] NOT NULL ,
[ItemId] [int] NOT NULL ,
[ItemCondition] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[ItemConditionDesc] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ItemMaster] (
[ItemId] [int] NOT NULL ,
[ItemName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ItemCondition] WITH NOCHECK ADD
CONSTRAINT [PK_ItemCondition] PRIMARY KEY CLUSTERED
(
[ItemConditionId]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ItemMaster] WITH NOCHECK ADD
CONSTRAINT [PK_ItemMaster] PRIMARY KEY CLUSTERED
(
[ItemId]
) ON [PRIMARY]
GO
Below are some sample inserts
INSERT INTO itemmaster (ItemId, ItemName)
VALUES (1,"CD ROM")
GO
INSERT INTO itemmaster (ItemId, ItemName)
VALUES (2,"Pen drive")
GO
INSERT INTO itemmaster (ItemId, ItemName)
VALUES (3,"DVD")
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (1,1,"Write once read many","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (2,1,"Silver coated","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (3,1,"700 MB","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (4,3,"Power DVD","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (5,3,"8.2 GB","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (6,2,"1 GB","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (7,2,"Write lock","")
GO
INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
ItemConditionDesc)
VALUES (8,2,"password protection","")
GO
Sincerely appreciate any help on this.
Thank you.
Regards,
KarthikHave a look at
http://www.aspfaq.com/show.asp?id=2462
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"Karthik" <Karthik@.discussions.microsoft.com> wrote in message
news:F279A4E0-72C3-466D-A122-66F885679485@.microsoft.com...
> Hi,
> I have two tables ItemMaster and ItemCondition. One item can have multiple
> conditions in the form of rows in ItemCondition. But while returning
> these, I
> would like to return it in the form of columns. Is that possible?
> Below is the DDL of my table structure
> CREATE TABLE [dbo].[ItemCondition] (
> [ItemConditionId] [int] NOT NULL ,
> [ItemId] [int] NOT NULL ,
> [ItemCondition] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [ItemConditionDesc] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS
> NULL
> ) ON [PRIMARY]
> GO
> CREATE TABLE [dbo].[ItemMaster] (
> [ItemId] [int] NOT NULL ,
> [ItemName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ItemCondition] WITH NOCHECK ADD
> CONSTRAINT [PK_ItemCondition] PRIMARY KEY CLUSTERED
> (
> [ItemConditionId]
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ItemMaster] WITH NOCHECK ADD
> CONSTRAINT [PK_ItemMaster] PRIMARY KEY CLUSTERED
> (
> [ItemId]
> ) ON [PRIMARY]
> GO
>
> Below are some sample inserts
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (1,"CD ROM")
> GO
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (2,"Pen drive")
> GO
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (3,"DVD")
>
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (1,1,"Write once read many","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (2,1,"Silver coated","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (3,1,"700 MB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (4,3,"Power DVD","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (5,3,"8.2 GB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (6,2,"1 GB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (7,2,"Write lock","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (8,2,"password protection","")
> GO
> Sincerely appreciate any help on this.
> Thank you.
> Regards,
> Karthik|||Hi
Usually you are better doing this on the client.
If there are a maximum number of possibilities then you can use self-joins
such as :
SELECT M.ItemId, M.ItemName, C1.ItemCondition, C2.ItemCondition,
C3.ItemCondition, ....
FROM ItemMaster I
LEFT JOIN ItemCondition C1 ON I.ItemId = C1.ItemId AND C1.ItemConditionId =
1
LEFT JOIN ItemCondition C2 ON I.ItemId = C2.ItemId AND C2.ItemConditionId =
2
LEFT JOIN ItemCondition C3 ON I.ItemId = C3.ItemId AND C3.ItemConditionId =
3
LEFT JOIN ItemCondition C4 ON I.ItemId = C4.ItemId AND C4.ItemConditionId =
4
LEFT JOIN ItemCondition C5 ON I.ItemId = C5.ItemId AND C5.ItemConditionId =
5
You may also want to look at:
http://www.winnetmag.com/SQLServer/...5608/15608.html
and other postings on CROSSTABs.
John
"Karthik" wrote:

> Hi,
> I have two tables ItemMaster and ItemCondition. One item can have multiple
> conditions in the form of rows in ItemCondition. But while returning these
, I
> would like to return it in the form of columns. Is that possible?
> Below is the DDL of my table structure
> CREATE TABLE [dbo].[ItemCondition] (
> [ItemConditionId] [int] NOT NULL ,
> [ItemId] [int] NOT NULL ,
> [ItemCondition] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [ItemConditionDesc] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS
> NULL
> ) ON [PRIMARY]
> GO
> CREATE TABLE [dbo].[ItemMaster] (
> [ItemId] [int] NOT NULL ,
> [ItemName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ItemCondition] WITH NOCHECK ADD
> CONSTRAINT [PK_ItemCondition] PRIMARY KEY CLUSTERED
> (
> [ItemConditionId]
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ItemMaster] WITH NOCHECK ADD
> CONSTRAINT [PK_ItemMaster] PRIMARY KEY CLUSTERED
> (
> [ItemId]
> ) ON [PRIMARY]
> GO
>
> Below are some sample inserts
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (1,"CD ROM")
> GO
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (2,"Pen drive")
> GO
> INSERT INTO itemmaster (ItemId, ItemName)
> VALUES (3,"DVD")
>
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (1,1,"Write once read many","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (2,1,"Silver coated","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (3,1,"700 MB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (4,3,"Power DVD","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (5,3,"8.2 GB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (6,2,"1 GB","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (7,2,"Write lock","")
> GO
> INSERT INTO ItemCondition (ItemConditionId, ItemId, ItemCondition,
> ItemConditionDesc)
> VALUES (8,2,"password protection","")
> GO
> Sincerely appreciate any help on this.
> Thank you.
> Regards,
> Karthik

Returning only the Header Row instead of all the relevant rows.

Hi All:

My below sub in application is returning only the Header Row instead of the relevant rows I guess therez problem in my "str" Syntax. However I fail to understand where exactly is it faultering.

PrivateSub btnSearch_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles btnSearch.Click

Try

con.Open()

Dim empIDAsString = txtEmpID.Text

Dim FNameAsString = txtFName.Text

Dim LNameAsString = txtLName.Text

Dim strAsString = "Select Emp_ID, Emp_FName,Emp_LName,Emp_Address1,Emp_HNo,Emp_MNo from Emp_Details where Emp_ID='" & empID & " ' Or Emp_LName='" & LName & " ' Or Emp_FName=' " & FName & "'"""Dim da1AsNew SqlDataAdapter(str, con)

da1.Fill(ds, "Emp_Details")

dgEmp.DataSource = ds

dgEmp.DataMember = "Emp_Details"

dgEmp.DataBind()

Finally

con.Close()

EndTry

EndSub

Thanks in Advance for your quick help.

Regards,

Brandy

It looks like you might have one too many extra spaces in your statement. Try this instead:

Dim strAs String =String.Format("SELECT Emp_ID, Emp_FName, Emp_LName, Emp_Address1, Emp_HNo, Emp_MNo FROM Emp_Details WHERE Emp_ID ='{0}' OR Emp_LName = '{1}' OR Emp_FName = '{2}'", empID, LName, FName)
|||

This works... Appreciate your kind help.

Returning Only 5 Rows

Not sure if this should be somewhere in the C# forum or the datagrid forum or in the SQL forum. I have a Windows Application written in C# that is accessing SQL Server 2005 (express I believe). The program loads up and the first form has a datagrid on it. The datagrid is bound to a sql query getting all rows from 1 of the tables, and displays them in the datagrid in descending order by date. Everything there is fine.

What I want to do is have the datagrid only show the last 5 entries (by date). I'm pretty sure this is possible but I'm not sure if it's done in the SQL query of if it's done somewhere in the datagrid (or somewhere in the binding).

Here is my SQL query so far...
[code]

SELECT transactionID, accountID, amount, type, description, notes, date
FROM Transactions
ORDER BY date DESC

[/code]

I believe in mySQL there was a LIMIT 5 parameter I could use, but that just produces an error here.

Thats an easy opne, have a look at the TOP operator:

SELECT TOP 5 transactionID, accountID, amount, type, description, notes, date
FROM Transactions
ORDER BY date DESC

Furtherone and due to the fact that you are using 2k5 you should have a look on ROW_NUMBER() which introduces a new feature of SQL 2k5 and can e.g. be used for pagination.

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

returning one single record rather than multiples

Hi

Is it possible to return the results of a query so that instead of
having say 10 rows its concatenated, eg

My query returns 'M' 10 times, can this be returned as 'M M M M M M M
M M M'?

Thanks
LeeLee (lee@.digital-interactive.com) writes:

Quote:

Originally Posted by

Is it possible to return the results of a query so that instead of
having say 10 rows its concatenated, eg
>
My query returns 'M' 10 times, can this be returned as 'M M M M M M M
M M M'?


In SQL 2005:

SELECT subtring(Ms, 1, datalength(Ms) / 2 - 1
FROM (SELECT col + ' ' AS [text()]
FROM tbl
FOR XML PATH('')) AS T(Ms)

This makes use of the XML functionality, and has the drawback that some
characters will be encoded.

In SQL 2000, you are unfortunately best of with a cursor.

--
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|||hi

I've just tried that (in SQL 2005)

SELECT subtring(Ms, 1, datalength(Ms) / 2 - 1
FROM (SELECT [company size] + ' ' AS [text()]
FROM results
FOR XML PATH('')) AS T(Ms)

and its returns errors, is that a working example?

Thanks
Lee|||The example from Erland is good, he was just sketching quickly to give you
an idea of how to solve your problem (and something to work on, since there
was no DDL posted). Here is a copy and paste extension to that:

CREATE TABLE tbl (col char(1))

INSERT INTO tbl VALUES ('M')
INSERT INTO tbl VALUES ('M')
INSERT INTO tbl VALUES ('M')
INSERT INTO tbl VALUES ('M')
INSERT INTO tbl VALUES ('M')

SELECT substring(Ms, 1, datalength(Ms) / 2 - 1)
FROM (SELECT col + ' ' AS [text()]
FROM tbl
FOR XML PATH('')) AS T(Ms)

DROP TABLE tbl

HTH,

Plamen Ratchev
http://www.SQLStudio.com

Tuesday, February 21, 2012

Returning multiple rows from a stored procedure

Hi,
I have the following stored procedure that does some processing and
puts the result in a temporary table. I tried several things that
procedure to display output that I can access with ADO.Net, but it
doesn't work. It doesn't even display the result in the query analyzer
unless I add SELECT @.ReturnFullName

Any help?

The stored procedure:
CREATE PROCEDURE sp_SEARCH_MULTIPLE_NAMES @.search4fatherOf
varchar(255), @.maximum_fathers int = 100, @.ReturnFullName varchar(255)
Output

...

SELECT @.ReturnFullName = name FROM #FULLNAME

---------------
To Execute the stored procedure:
DECLARE @.test varchar(255)
EXEC sp_SEARCH_MULTIPLE_NAMES @.search4fatherof='????',
@.returnfullname=@.test
PRINT CONVERT(varchar(255), @.test)On 22 May 2006 10:11:11 -0700, Wael wrote:

>Hi,
>I have the following stored procedure that does some processing and
>puts the result in a temporary table. I tried several things that
>procedure to display output that I can access with ADO.Net, but it
>doesn't work.

Hi Wael,

If you want to return a resultset to the client, just add a command such
as the one below in the appropriate place in your stored procedure:

SELECT Co11, Col2, ...
FROM #TempTable
-- WHERE ???

This will expose the results of this query as a recordset to the client.

>The stored procedure:
>CREATE PROCEDURE sp_SEARCH_MULTIPLE_NAMES @.search4fatherOf
>varchar(255), @.maximum_fathers int = 100, @.ReturnFullName varchar(255)
>Output

Please choose a different name for your stored procedure. The "sp_"
prefix is reserved for Microsoft-supplied system stored procedures. If
you use this prefix for your own procedures, you will lose some
performance (because SQL Server will first try to find the procedure in
the master database), and yoou run the risk of unexpected effects if
Microsoft decides to use the same name for a system stored procedure
included in the next version, service pack or patch.

>...
>SELECT @.ReturnFullName = name FROM #FULLNAME

If the #FULLNAME table holds more than one row, the effect of this
sttatement will be to assign the name from each of those rows in turn to
the variable, constantly replacing the "previous" value. Only the value
from the row that's processed last will stick. Since order of processing
of the rows is undefined, the net result of this statement will be to
waste some time and assign one "randomply chosen" name from the table to
@.ReturnFullName.

>---------------
>To Execute the stored procedure:
>DECLARE @.test varchar(255)
>EXEC sp_SEARCH_MULTIPLE_NAMES @.search4fatherof='??',
>@.returnfullname=@.test

You have to include the OUTPPUT keyword on the call as well:

EXEC sp_SEARCH_MULTIPLE_NAMES
@.search4fatherOf = '??',
@.ReturnFullName = @.test OUTPUT

>PRINT CONVERT(varchar(255), @.test)

No need for the CONVERT - @.test is already typed as varchar(255).

--
Hugo Kornelis, SQL Server MVP|||Hi Hugo,

Thanks for your response. My ultimate goal is to return all the rows
not just one. Is that doable?

Also even with the select statement, the results are not accessible to
ADO.Net even though I can see them in the query analyzer.

THanks
Wael|||Wael (sedky@.rocketmail.com) writes:
> Thanks for your response. My ultimate goal is to return all the rows
> not just one. Is that doable?

Yes, that's a very normal thing to do.

> Also even with the select statement, the results are not accessible to
> ADO.Net even though I can see them in the query analyzer.

So how does your ADO .Net code look like?

--
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|||Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSearch.Click
Dim drParents As SqlDataReader
Dim cmdParents As New SqlCommand
Dim spParamenters As New SqlParameter
cnParents.ConnectionString = Constants.ConnectionString
cmdParents.CommandType = CommandType.StoredProcedure
cmdParents.CommandText = "sp_SEARCH_MULTIPLE_NAMES"
spParamenters.ParameterName = "@.search4fatherOf"
spParamenters.ParameterName = "@.returnfullname"
cmdParents.Parameters("@.search4fatherOf").Value =
txtSearchParent.Text
cmdParents.Parameters("@.returnfullname").Value = "test"
spParamenters.SqlDbType = SqlDbType.VarChar
cmdParents.Parameters.Add(spParamenters)
cnParents.Open()
cmdParents.Connection = cnParents
drParents = cmdParents.ExecuteReader
Response.Write(drParents.GetString(0))
drParents.Close()

End Sub

I have to give the output parameter a value otherwise it doesn't work.
Here is the error i get:
An SqlParameter with ParameterName '@.search4fatherOf' is not contained
by this SqlParameterCollection.

Before I used the parameters I used to get an error that there was no
data. I don't see why I should be using 'Output' since I have to use
the SELECT statement anyway.|||Wael (sedky@.rocketmail.com) writes:

> Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles btnSearch.Click
> Dim drParents As SqlDataReader
> Dim cmdParents As New SqlCommand
> Dim spParamenters As New SqlParameter
> cnParents.ConnectionString = Constants.ConnectionString
> cmdParents.CommandType = CommandType.StoredProcedure
> cmdParents.CommandText = "sp_SEARCH_MULTIPLE_NAMES"
> spParamenters.ParameterName = "@.search4fatherOf"
> spParamenters.ParameterName = "@.returnfullname"
> cmdParents.Parameters("@.search4fatherOf").Value =
> txtSearchParent.Text
> cmdParents.Parameters("@.returnfullname").Value = "test"
>...
> I have to give the output parameter a value otherwise it doesn't work.
> Here is the error i get:
> An SqlParameter with ParameterName '@.search4fatherOf' is not contained
> by this SqlParameterCollection.

What it says. You have defined a parameter, set the name of it twice.
But you have never added it to the Parameters collection. To that end
you need to use the .Add method.

Apparently, you are very new to ADO .Net programming. Unfortunately,
newsgroups are not good venues for learning things from scratch, because
the answer will be small tidbits here and there. You are better off
trying to find some book with exercises and samples to get you going.
Or find some classes you can take in your area.

--
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