Showing posts with label records. Show all posts
Showing posts with label records. Show all posts

Friday, March 30, 2012

return duplicate records

Hello experts,

I'm trying the run the following query with specific intentions.

I would like the query to return 5 results; i.e., 4 distinct and one
duplicate. I am only getting, however, 4 distinct records. I would
like the results from the '007' id to spit out twice.

I'm not using 'distinct,' and I've tried 'all.' I realize that I
could put my 5 employee id's in a table and do a left or right join; I
would like to avoid that, however. Any thoughts?

Select
Employee_last_name,
Employee_first_name

Quote:

Originally Posted by

>From tbl_employee


Where employee_id in (
'009',
'008',
'007',
'007',
'006'
);

alexAlex,

There are a few solutions. Two are (might have typos, but you should be
able to get the idea):

select Employee_last_name, Employee_first_name
from tbl_employee
join (
select '009' as id union all
select '008' as id union all
select '007' as id union all
select '007' as id union all
select '006' as id
) as IDs
on IDs.id = tbl_employee.employee_id

or to make the specification of ids simpler:

declare @.ids varchar(1000)
set @.ids = '009008007007006'
declare @.idlength int
set @.idlength = 3

select Employee_last_name, Employee_first_name
from tbl_employee
join a_permanent_table_of_integers_from_0_to_whatever as Nums
on employee_id = substring(@.ids,@.idlength*n+1,@.idlength)
and n < len(@.ids)/@.idlength
-- [n] is the column name for the permanent table and should
-- be that tables primary key

-- Steve Kass
-- Drew University
-- http://www.stevekass.com
alex wrote:

Quote:

Originally Posted by

Hello experts,
>
I'm trying the run the following query with specific intentions.
>
I would like the query to return 5 results; i.e., 4 distinct and one
duplicate. I am only getting, however, 4 distinct records. I would
like the results from the '007' id to spit out twice.
>
I'm not using 'distinct,' and I've tried 'all.' I realize that I
could put my 5 employee id's in a table and do a left or right join; I
would like to avoid that, however. Any thoughts?
>
Select
Employee_last_name,
Employee_first_name

Quote:

Originally Posted by

>>From tbl_employee


Where employee_id in (
'009',
'008',
'007',
'007',
'006'
);
>
alex
>

|||>I would like the query to return 5 results; i.e., 4 distinct and one duplicate. <<

The easy way is a UNION, based on a guess about the DDL you did bother
to post and the uniquness of emp_id:

SELECT last_name, first_name
FROM Personnel
WHERE emp_id IN ('009', '008', '007', '006')
UNION
SELECT last_name, first_name
FROM Personnel
WHERE emp_id = '007'|||--CELKO-- (jcelko212@.earthlink.net) writes:

Quote:

Originally Posted by

Quote:

Originally Posted by

Quote:

Originally Posted by

>>I would like the query to return 5 results; i.e., 4 distinct and one


duplicate. <<

Quote:

Originally Posted by

>
The easy way is a UNION, based on a guess about the DDL you did bother
to post and the uniquness of emp_id:
>
SELECT last_name, first_name
FROM Personnel
WHERE emp_id IN ('009', '008', '007', '006')
UNION
SELECT last_name, first_name
FROM Personnel
WHERE emp_id = '007'


Joe, I thought you knew SQL? This query will not return the results
that Alex was asking for.

Why is left as an exercise to the reader.

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

Return all rows works partially

I encounter a problem where returning all rows from a certain table in
SQL server 2000, the records sometimes can be return sometimes not.
In Enterprise Manager, I browse to a table, then I right click on it,
click "Open table > Return all rows" ... it just keep waiting until it
timeout. It didn't return any result. But when I "Return top" ... with
returning top 71, the records will shown. When I try to return top 72,
it happen again, with no result returned and timeout. I'd try a few
times with different value, it always happen when I try to return rows
until row 72.
I'd try it in Query Analyzer, it's the same.
It return rows when "SELECT TOP 71 * FROM theTableName"
but no response when "SELECT TOP 72 * FROM theTableName"
Anyone encounter this problem before? Is it the index of that table
corrupted? Or values inside that rows cannot be return?
Any idea how to solve this?
Thanks.
Peter CCH
Possibly someone has a lock on the row which will be read as row number 72 by the selected execution
plan. Check using sp_lock, sp_who etc.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133516672.695691.143760@.g14g2000cwa.googlegr oups.com...
>I encounter a problem where returning all rows from a certain table in
> SQL server 2000, the records sometimes can be return sometimes not.
> In Enterprise Manager, I browse to a table, then I right click on it,
> click "Open table > Return all rows" ... it just keep waiting until it
> timeout. It didn't return any result. But when I "Return top" ... with
> returning top 71, the records will shown. When I try to return top 72,
> it happen again, with no result returned and timeout. I'd try a few
> times with different value, it always happen when I try to return rows
> until row 72.
> I'd try it in Query Analyzer, it's the same.
> It return rows when "SELECT TOP 71 * FROM theTableName"
> but no response when "SELECT TOP 72 * FROM theTableName"
> Anyone encounter this problem before? Is it the index of that table
> corrupted? Or values inside that rows cannot be return?
> Any idea how to solve this?
> Thanks.
>
> Peter CCH
>
|||But I'm the only one user who access to that database while I doing
that.
Peter CCH
|||I'd still check for blocking. It could be an open transaction hanging around or something, you never
know. Other possible reasons:
73 vs 72 rows lead to different execution plans. Check using estimated execution plan.
Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133521175.165593.145330@.g49g2000cwa.googlegr oups.com...
> But I'm the only one user who access to that database while I doing
> that.
>
> Peter CCH
>
|||Tibor Karaszi wrote:
> I'd still check for blocking. It could be an open transaction hanging
> around or something, you never know. Other possible reasons:
> 73 vs 72 rows lead to different execution plans. Check using
> estimated execution plan.
> Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
Could as well be a too low timeout value, couldn't it?
robert

Return all rows works partially

I encounter a problem where returning all rows from a certain table in
SQL server 2000, the records sometimes can be return sometimes not.
In Enterprise Manager, I browse to a table, then I right click on it,
click "Open table > Return all rows" ... it just keep waiting until it
timeout. It didn't return any result. But when I "Return top" ... with
returning top 71, the records will shown. When I try to return top 72,
it happen again, with no result returned and timeout. I'd try a few
times with different value, it always happen when I try to return rows
until row 72.
I'd try it in Query Analyzer, it's the same.
It return rows when "SELECT TOP 71 * FROM theTableName"
but no response when "SELECT TOP 72 * FROM theTableName"
Anyone encounter this problem before? Is it the index of that table
corrupted? Or values inside that rows cannot be return?
Any idea how to solve this?
Thanks.
Peter CCHPossibly someone has a lock on the row which will be read as row number 72 by the selected execution
plan. Check using sp_lock, sp_who etc.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133516672.695691.143760@.g14g2000cwa.googlegroups.com...
>I encounter a problem where returning all rows from a certain table in
> SQL server 2000, the records sometimes can be return sometimes not.
> In Enterprise Manager, I browse to a table, then I right click on it,
> click "Open table > Return all rows" ... it just keep waiting until it
> timeout. It didn't return any result. But when I "Return top" ... with
> returning top 71, the records will shown. When I try to return top 72,
> it happen again, with no result returned and timeout. I'd try a few
> times with different value, it always happen when I try to return rows
> until row 72.
> I'd try it in Query Analyzer, it's the same.
> It return rows when "SELECT TOP 71 * FROM theTableName"
> but no response when "SELECT TOP 72 * FROM theTableName"
> Anyone encounter this problem before? Is it the index of that table
> corrupted? Or values inside that rows cannot be return?
> Any idea how to solve this?
> Thanks.
>
> Peter CCH
>|||But I'm the only one user who access to that database while I doing
that.
Peter CCH|||I'd still check for blocking. It could be an open transaction hanging around or something, you never
know. Other possible reasons:
73 vs 72 rows lead to different execution plans. Check using estimated execution plan.
Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133521175.165593.145330@.g49g2000cwa.googlegroups.com...
> But I'm the only one user who access to that database while I doing
> that.
>
> Peter CCH
>|||Tibor Karaszi wrote:
> I'd still check for blocking. It could be an open transaction hanging
> around or something, you never know. Other possible reasons:
> 73 vs 72 rows lead to different execution plans. Check using
> estimated execution plan.
> Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
Could as well be a too low timeout value, couldn't it?
robertsql

Wednesday, March 28, 2012

Return all rows works partially

I encounter a problem where returning all rows from a certain table in
SQL server 2000, the records sometimes can be return sometimes not.
In Enterprise Manager, I browse to a table, then I right click on it,
click "Open table > Return all rows" ... it just keep waiting until it
timeout. It didn't return any result. But when I "Return top" ... with
returning top 71, the records will shown. When I try to return top 72,
it happen again, with no result returned and timeout. I'd try a few
times with different value, it always happen when I try to return rows
until row 72.
I'd try it in Query Analyzer, it's the same.
It return rows when "SELECT TOP 71 * FROM theTableName"
but no response when "SELECT TOP 72 * FROM theTableName"
Anyone encounter this problem before? Is it the index of that table
corrupted? Or values inside that rows cannot be return?
Any idea how to solve this?
Thanks.
Peter CCHPossibly someone has a lock on the row which will be read as row number 72 b
y the selected execution
plan. Check using sp_lock, sp_who etc.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133516672.695691.143760@.g14g2000cwa.googlegroups.com...
>I encounter a problem where returning all rows from a certain table in
> SQL server 2000, the records sometimes can be return sometimes not.
> In Enterprise Manager, I browse to a table, then I right click on it,
> click "Open table > Return all rows" ... it just keep waiting until it
> timeout. It didn't return any result. But when I "Return top" ... with
> returning top 71, the records will shown. When I try to return top 72,
> it happen again, with no result returned and timeout. I'd try a few
> times with different value, it always happen when I try to return rows
> until row 72.
> I'd try it in Query Analyzer, it's the same.
> It return rows when "SELECT TOP 71 * FROM theTableName"
> but no response when "SELECT TOP 72 * FROM theTableName"
> Anyone encounter this problem before? Is it the index of that table
> corrupted? Or values inside that rows cannot be return?
> Any idea how to solve this?
> Thanks.
>
> Peter CCH
>|||But I'm the only one user who access to that database while I doing
that.
Peter CCH|||I'd still check for blocking. It could be an open transaction hanging around
or something, you never
know. Other possible reasons:
73 vs 72 rows lead to different execution plans. Check using estimated execu
tion plan.
Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Peter CCH" <petercch.wodoy@.gmail.com> wrote in message
news:1133521175.165593.145330@.g49g2000cwa.googlegroups.com...
> But I'm the only one user who access to that database while I doing
> that.
>
> Peter CCH
>|||Tibor Karaszi wrote:
> I'd still check for blocking. It could be an open transaction hanging
> around or something, you never know. Other possible reasons:
> 73 vs 72 rows lead to different execution plans. Check using
> estimated execution plan.
> Table corruption. Check using DBCC CHECKDB or DBCC CHECKTABLE.
Could as well be a too low timeout value, couldn't it?
robert

Return All Rows

Hello Again,

Here is my situation..

I have a datareader that reads through all the records that satisfy my query condition... Once i have my records in the datareader i want to run through all of the values from it and form HTML rows, how do i do it? Following is the code that i have written

CustID = Session("CustCode")
viewSqlStr = "Select [Lead Title], [Lead Date] from [Lead Info] Where [Customer ID] = '" & CustID & "'"
objCommand = New SqlCommand(viewSqlStr, objConn)
objConn.Open()
objDR = objCommand.ExecuteReader()

Then in the HTML i do:

<% While objDR.Read() %>
<tr>
<td class="f10" bgcolor="#ffffff" valign="top">Edit</td>
<td class="f10" bgcolor="#ffffff" valign="top"><%= objDR("Lead Title") %></td>
<td class="f10" bgcolor="#ffffff" valign="top"><%= objDR("Lead Date") %></td>
</tr>
<% End While %
When i do this... inspite of having more than one records in the database.. only the last record is displayed on the screen. how do i make it display all the records here? i know in asp ado there was a movenext statement... what goes here? can someone pls help me with this so that all the records can be displayed here?

Thanks in advance,
~ssBinding this to a datagrid would probably be much faster...|||What this will do is to read through all of them - - forward only - - then, the last one in the list gets left on the screen for you to see.

What you want can be done with a Repeater or a DataList....Create the Item Template, then, instead of objDR.Read - - just bind the dataReader to the DataList or Repeater.

Check out:
http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=dListdReader

It's not exactly your scenario, with the Table, etc, but it will show you how to use a DataList with a DataReader. You can add a HeaderTemplate for the Column HEaders and then one row and a cell for each item you want to show, in the ItemTemplate.

However, it's MUCH easier to use a DataGrid - - - skipping all the Table/Row/Cell stuff - - it's done automatically with a DataGrid

Return all records in 15 min intervals.

Hello All,

First off thanks to all who try to help me.

I have a table with a date timestamp that includes the minute in 24 hour format..
I need to return all the records in the date range between '1/1/2007' and '1/31/2007' which is very simple.
The part I am having a hard time with is in the where clause.
I retrieve all the records for the date range into a #temptable
Now I need to sort these into 15 minute intervals based on the timestamp, but the sproc does'nt get passed a time only two dates also I need to provide a count of the records returned.

I have tried to create a temp table with 96 records being that there are 96 intervals of 15 minutes in 24 hours.
and using that as kinda a join.

I have tried to do something with datediff(_) with a dateadd(_)+15 in the where clause.

I also tried a loop 96 times.

I know there are a few ways to do it.I just dont know which ones.

I've only been using tsql for 2 months and have come pretty far, but this situation evades me.

Please enlighten me with your infinite wisdom of the tsql language. Help !

Is this the idea?

declare @.sampleData table
( rid integer primary key,
sampleDate datetime
)

insert into @.sampleData
select iter,
cast ('12/25/6' as datetime) + 70 * dbo.rand()
from small_iterator (nolock) -- A table of integers 1-32767

select top 5
rid,
sampleDate,
p.startOfInterval,
p.endOfInterval
from @.sampleData a
inner join
( select iter,
cast ((iter-1) * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as startOfInterval,
cast (iter * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as endOfInterval
from small_iterator (nolock) -- a table of integers 1-32767
where iter <= 96
) p
on sampleDate >= '1/1/7'
and sampleDate < '2/1/7'
and cast(cast(sampleDate as binary(4)) as datetime) >= p.startOfInterval
and cast(cast(sampleDate as binary(4)) as datetime) < p.endOfInterval
order by rid

-- rid sampleDate startOfInterval endOfInterval
-- -- - -
-- 1 2007-01-02 14:58:52.183 1900-01-01 14:44:59.997 1900-01-01 15:00:00.000
-- 3 2007-01-30 08:00:32.787 1900-01-01 08:00:00.000 1900-01-01 08:15:00.000
-- 4 2007-01-16 19:59:58.257 1900-01-01 19:45:00.000 1900-01-01 19:59:59.997
-- 5 2007-01-04 10:34:13.883 1900-01-01 10:30:00.000 1900-01-01 10:44:59.997
-- 8 2007-01-22 08:14:12.333 1900-01-01 08:00:00.000 1900-01-01 08:15:00.000


select left(convert (varchar(8), p.startOfInterval, 108), 5) as startOfInterval,
left(convert (varchar(8), p.endOfInterval, 108), 5) as endOfInterval,
count(*) as intervalCount
from @.sampleData a
inner join
( select iter,
cast ((iter-1) * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as startOfInterval,
cast (iter * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as endOfInterval
from small_iterator (nolock) -- a table of integers 1-32767
where iter <= 96
) p
on sampleDate >= '1/1/7'
and sampleDate < '2/1/7'
and cast(cast(sampleDate as binary(4)) as datetime) >= p.startOfInterval
and cast(cast(sampleDate as binary(4)) as datetime) < p.endOfInterval
group by p.startOfInterval, p.endOfInterval
order by p.StartOfInterval

-- startOfInterval endOfInterval intervalCount
-- - -
-- 00:00 00:15 151
-- 00:15 00:30 158
-- 00:30 00:45 134
-- ...
-- 23:30 23:44 145
-- 23:44 00:00 158

|||

Getting Closer..

Thank you very much Kent.
I wish I could write code like that in Tsql and actually "Get it to work" for me.

I need the data to look like this which for the most part the above does.

Date 1/1/2007 <Whatever user chooses

Time Interval Number Calls

12:00 12:15 147
12:15 12:30 117
12:30 12:45 215

The existing data I have looks like this for the timestamp field.

12/22/2003 9:29:00 AM
1/5/2004 1:31:00 PM
7/2/2003 3:53:00 PM
7/7/2003 1:27:00 PM


I have thought about parsing out the strings then back converting them but with sql we shouldnt have to do that.
I'm going to attempt to plug the above code in and see what I can do with it. More suggestions are welcome !

|||Do you need me to post my dbo.rand() function and small_iterator table?|||

You could change the SELECT list to that shown below.

Displaying the date above the output results (i.e. handling presentation) isn't what SQL Server is good at. It's far better to handle this in the client code or in Reporting Services.

Chris

SELECT CAST(DATEPART(hh, p.startOfInterval) AS VARCHAR(2)) + ':'

+ CAST(DATEPART(mi, p.startOfInterval) AS VARCHAR(2)) + ' '

+ CAST(DATEPART(hh, e.endOfInterval) AS VARCHAR(2)) + ':'

+ CAST(DATEPART(mi, e.endOfInterval) AS VARCHAR(2)) AS [Time Interval],

COUNT(*) AS [Number Calls]

|||

Kent - I know you weren't talking to me, but it would be good if you could. I've noticed you use small_iterator in a number of your posts.

Is it just a table of sequential integers?

Cheers
Chris

|||

Yes, small_iterator is a list of integers 1-32767; stand by and I will post this stuff. Here is another shot at your summary (the SMALL_ITERATOR and dbo.rand() will follow in a minute):

declare @.searchDate datetime
set @.searchDate = '3/1/7'

declare @.sampleData table
( rid integer primary key,
sampleDate datetime
)

insert into @.sampleData
select iter,
cast ('12/25/6' as datetime) + 70 * dbo.rand()
from small_iterator (nolock) -- A table of integers 1-32767


select left(convert (varchar(8), p.startOfInterval, 108), 5) + ' ' +
left(convert (varchar(8), p.endOfInterval, 108), 5) + ' ' as [ Time Interval],
count(*) as intervalCount
from @.sampleData a
inner join
( select iter,
cast ((iter-1) * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as startOfInterval,
cast (iter * cast (cast ('0:15:00.000' as datetime) as float) as datetime)
as endOfInterval
from small_iterator (nolock) -- a table of integers 1-32767
where iter <= 96
) p
on sampleDate >= @.searchDate
and sampleDate < (@.searchDate + 1)
and cast(cast(sampleDate as binary(4)) as datetime) >= p.startOfInterval
and cast(cast(sampleDate as binary(4)) as datetime) < p.endOfInterval
group by p.startOfInterval, p.endOfInterval
order by p.StartOfInterval

-- Time Interval intervalCount
-- -- -
-- 00:00 00:15 4
-- 00:15 00:30 6
-- 00:30 00:45 6
-- ...
-- 23:30 23:44 2
-- 23:44 00:00 2

|||

Here is my small_iterator table; it is simply a table of numbers. To get some ideas about tables of numbers, give this website a look:

http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html

create table dbo.SMALL_ITERATOR
( iter smallint not null
constraint PK_SMALL_ITERATOR primary key
)
go


/* -- */
/* This routine is used to populate the small_iterator table. */
/* This query ran in 1 second in development and should run at */
/* a similar speed in production. */
/* -- */

truncate table SMALL_ITERATOR

insert into small_iterator
select number from master.dbo.spt_values (nolock)
where name is null
and number <= 255

insert into small_iterator
select 256 * j.iter + i.iter
from small_iterator i
inner join small_iterator j
on j.iter > 0
and j.iter <= 127
order by 256 * j.iter + i.iter

delete from small_iterator where iter = 0

select count(*) [count],
min (iter) [min iterator],
max (iter) [max iterator]
from SMALL_ITERATOR

go

dbcc dbreindex (small_iterator, '', 100)
go

update statistics small_iterator
go

exec sp_recompile small_iterator
go

|||

Here is my RAND scalar UDF; it comes in handy at times for generating mock data:

create view dbo.vRand
as
select rand () as vRand
go

create function dbo.rand ()
returns float
as
begin

return (select vRand from dbo.vRand)

end

go

create function dbo.randList
( @.pm_listSize integer
)
returns @.randList table
( rid integer,
iRand float
)
as
begin

declare @.upperBound integer

set @.upperBound = ceiling (convert(float, (@.pm_listSize+1))
/ convert (float, 32767))

insert into @.randList
select 32767*(j.iter-1) + i.iter - 1 as rid,
dbo.rand() as iRand
from small_iterator i (nolock)
inner join small_iterator j (nolock)
on j.iter <= @.upperBound
and 32767*(j.iter-1) + i.iter - 1 <= @.pm_listSize
and 32767*(j.iter-1) + i.iter - 1 > 0


return

end

go

|||

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=81913&SiteID=1

declare @.interval int
set @.interval=30

select dateadd(minute,floor(datediff(minute,0,OrderDate)/@.interval)*@.interval,0) [dt],
count(*) [cnt]
from Northwind..Orders
group by dateadd(minute,floor(datediff(minute,0,OrderDate)/@.interval)*@.interval,0)
order by 1

This is looking like it's going to work for my needs just have to tweak it a bit more..

Thanks to all who helped. One day I'll be able to help with tsql instead of just VB and ASP

Monday, March 26, 2012

retrive all records within the Case statment

i want to filter a table by a view using a defind function
for example:
select * from person
where dbo.person.company like case CmpName()
when 'all' then '%'
else CmpName()
end
prblem is that '%' doesn't show the records with NULL value
how can i
thanks
samTry using IS NULL clause
This posting is provided "AS IS" with no warranties, and confers no rights.
Regards,
Uwa Agbonile[MSFT]
"Sam" <focus10@.zahav.net.il> wrote in message
news:uWyStcqYFHA.3364@.TK2MSFTNGP12.phx.gbl...
> i want to filter a table by a view using a defind function
> for example:
> select * from person
> where dbo.person.company like case CmpName()
> when 'all' then '%'
> else CmpName()
> end
> prblem is that '%' doesn't show the records with NULL value
> how can i
> thanks
> sam
>|||"IS NULL" is not working with "=" , or "Like" operators
so i can not use it with the "CASE" statment
"Uwa Agbonile [MSFT]" <uwaag@.online.microsoft.com> wrote in message
news:ez3NxhwYFHA.2572@.TK2MSFTNGP14.phx.gbl...
> Try using IS NULL clause
> --
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> Regards,
> Uwa Agbonile[MSFT]
> "Sam" <focus10@.zahav.net.il> wrote in message
> news:uWyStcqYFHA.3364@.TK2MSFTNGP12.phx.gbl...
>

retrive all records within the Case statment

i want to filter a table by a view using a defind function
for example:
select * from person
where dbo.person.company like case CmpName()
when 'all' then '%'
else CmpName()
end
prblem is that '%' doesn't show the records with NULL value
how can i
thanks
sam
Try using IS NULL clause
This posting is provided "AS IS" with no warranties, and confers no rights.
Regards,
Uwa Agbonile[MSFT]
"Sam" <focus10@.zahav.net.il> wrote in message
news:uWyStcqYFHA.3364@.TK2MSFTNGP12.phx.gbl...
> i want to filter a table by a view using a defind function
> for example:
> select * from person
> where dbo.person.company like case CmpName()
> when 'all' then '%'
> else CmpName()
> end
> prblem is that '%' doesn't show the records with NULL value
> how can i
> thanks
> sam
>
|||"IS NULL" is not working with "=" , or "Like" operators
so i can not use it with the "CASE" statment
"Uwa Agbonile [MSFT]" <uwaag@.online.microsoft.com> wrote in message
news:ez3NxhwYFHA.2572@.TK2MSFTNGP14.phx.gbl...
> Try using IS NULL clause
> --
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> Regards,
> Uwa Agbonile[MSFT]
> "Sam" <focus10@.zahav.net.il> wrote in message
> news:uWyStcqYFHA.3364@.TK2MSFTNGP12.phx.gbl...
>
sql

Friday, March 23, 2012

Retrieving the First N Records from a SQL Query in VS 2005

Hi,

first off, I'm a TOTAL novice at this stuff, I'm just currently blundering my way through a complex site to learn stuff.

I'm trying to call the newest addition to a SQL database into a webpage, in this case, it'll be 'newest user', one result only. I've done several other data retrival sections using a datatable, but the guy who was helping me though it is unavailable at the moment and I get the feeling I've jumped into the deepend slightly.

Could anyone give me an example of how retrieving the First N Records from SQL should look in VS? Does it need to be in a data table or can it go in a label?

Sorry if this is somewhat vague, but as I said, I've really only been using VS for a week!

SELECT TOP 1 FROM [TableName] ORDER BY timestamp

Hope this helps

Al

|||

Hi,

Using the Top keyword is the solution. But the use of TOP has changed between SQL2K and SQL2K5.

In SQL2k you were not able to use TOP @.N which means you can not dynamically set the record count for "TOP"

Check the article for TOP @.N usage athttp://kodyaz.com/articles/article.aspx?articleid=2

Also have a look at the new t-sql functions named "Window Functions". Also you can find some samples athttp://kodyaz.com/articles/article.aspx?articleid=19

Eralper

http://www.eralper.com

|||

Cheers Al,

trouble is, I'm unsure as to where it needs to go! As I said, I'm pretty rubbish at this VS lark so far.

Should I be using a datatable to display the information, or because its only a single result I want pulling back, can it be done in a label?

Currently, I have this working to bring back a compleate list of users, but on another page, I need to bring back only the newest. Once again, sorry if I appear dense, learning curve and all that;


CODE:

Dim SiteuserAsNew mySite.Siteuser

dlDataList.DataSource = Siteuser.List

dlDataList.DataBind()

HTML:

<asp:DataListID="dlDataList"runat="server">

<ItemTemplate>

<asp:LabelID="HyperLink1"runat="server"NavigateUrl='<%#Eval("SiteuserID", "viewuser.aspx?SiteuserID={0}" ) %>'Text='<%#Eval("title") %>'Font-Italic="true"></asp:Label><asp:HyperLinkID="hlkUser"runat="server"NavigateUrl='<%#Eval("SiteuserID", "viewuser.aspx?SiteuserID={0}" ) %>'Text='<%#Eval("fullname") %>'></asp:HyperLink></tr>

</ItemTemplate>

</asp:DataList>

sql

Wednesday, March 21, 2012

retrieving selected join records

Hi,
I have the folowing 3 (SS2005) tables:

CREATE TABLE [dbo].[tblSubscription](
[SubscriptionID] [int] IDENTITY(1000000,1) NOT NULL,
[SubscriberID] [int] NOT NULL,
[Status] [int] NOT NULL,
[JournalID] [int] NOT NULL,

CREATE TABLE [dbo].[tblTransaction](
[TransactionID] [bigint] IDENTITY(100000000,1) NOT NULL,
[TransactionTypeID] [int] NOT NULL,
[SubscriptionID] [int] NOT NULL,
[Created] [datetime] NOT NULL,

CREATE TABLE [dbo].[tblMailing](
[MialingID] [bigint] IDENTITY(1000000000,1) NOT NULL,
[SubscriptionID] [int] NOT NULL,
[MailTypeID] [int] NOT NULL,
[MailDate] [datetime] NOT NULL

So for each subscription there can be 1 or more transactions and 0 or
more mailings, and the mailings are not necassarily related to the
transactions. What I am having difficulty doing is this:

I wish to select tblMailing.MailingID, tblMailing.MailDate,
tblMailing.SubscriptionID (or tblSubscription.SubscriptionID),
tblSubscription.SubscriberID, tblSubscription.Status,
tblTransaction.TransactionID, tblTransaction.Created, but I only wish
to retrieve rows from the transaction table where
tblTransaction.Created is the latest dated transaction for that
subscription.
I.E. (maybe this makes more sense..:) I wish to select all rows from
tblMailing along with each mailing's relevent subscription details,
including details of the LATEST TRANSACTION for each of those
subscriptions.

I am currently working along the lines of MAX(tblTransaction.Created)
and possibly GROUP BY in a subquery, but cannot quite figure out the
logic.

Any help appreciated.

Thanks, KoG

King:

Are you wanting the subscription record to appear in the report even if there are as of yet no mailings? That is, do I need to use an outer join or an inner join? I am for the moment assuming that you want the inner join.


Dave

|||

set nocount on
declare @.tblSubscription table
( subscriptionID integer not null,
subscriberID integer not null,
status integer not null,
journalID integer not null,
primary key (subscriptionID)
)

declare @.tblTransaction table
( transactionID integer not null,
transactionTypeId integer not null,
subscriptionID integer not null,
created datetime not null
primary key (transactionID),
unique (subscriptionID, transactionID)
)

declare @.tblMailing table
( mailingId bigint not null,
subscriptionID integer not null,
mailTypeId integer not null,
mailDate datetime not null,
primary key (mailingID),
unique (subscriptionId, mailingId)
)

insert into @.tblSubscription values (1000001, 1000001, 1, 1)
insert into @.tblSubscription values (1000002, 1000002, 1, 1)
insert into @.tblSubscription values (1000003, 1000001, 2, 1)
--select * from @.tblSubscription

insert into @.tblTransaction values (1000001, 1, 1000001, '3/15/6' )
insert into @.tblTransaction values (1000002, 2, 1000001, '4/7/6' )
insert into @.tblTransaction values (1000003, 1, 1000002, '4/3/6' )
insert into @.tblTransaction values (1000004, 1, 1000003, '5/8/6' )
insert into @.tblTransaction values (1000005, 2, 1000003, '10/14/6')
insert into @.tblTransaction values (1000006, 4, 1000003, '9/1/6' )
--select * from @.tblTransaction

insert into @.tblMailing values (1000001, 1000001, 1, '3/15/6' )
insert into @.tblMailing values (1000002, 1000001, 2, '4/4/6' )
insert into @.tblMailing values (1000003, 1000003, 1, '5/9/6' )
insert into @.tblMailing values (1000004, 1000003, 3, '9/3/6' )
--select * from @.tblMailing

--set statistics io on
select m.mailingId,
m.MailDate,
s.subscriptionId,
s.subscriberId,
s.Status,
t.TransactionId,
t.created
from @.tblSubscription s
inner join @.tblMailing m
on s.subscriptionId = m.subscriptionId
inner join
( select q.subscriptionId,
q.transactionId,
row_number () over
( partition by q.subscriptionId
order by q.created desc, q.transactionId desc
) as Seq,
created
from @.tblTransaction q
) t
on t.subscriptionId = s.subscriptionId
and seq = 1
--set statistics io off


-- -- Sample Output: -

-- mailingId MailDate subscriptionId subscriberId Status TransactionId created
-- -- -- -- -- - --
-- 1000001 2006-03-15 00:00:00.000 1000001 1000001 1 1000002 2006-04-07 00:00:00.000
-- 1000002 2006-04-04 00:00:00.000 1000001 1000001 1 1000002 2006-04-07 00:00:00.000
-- 1000003 2006-05-09 00:00:00.000 1000003 1000001 2 1000005 2006-10-14 00:00:00.000
-- 1000004 2006-09-03 00:00:00.000 1000003 1000001 2 1000005 2006-10-14 00:00:00.000

|||Hi Dave,

I only wish to select subscription rows where there is a mailing associated with the subscription. In fact, the driver of the query should be the mailings table, so for each row in tblMailing get the relevent subscription (& latest transaction) data. That means there may be several rows where the data in the subscription-related columns (& hence transaction related ones too) are the same, as a subscription may have several mailings.

I assume that means the inner join is required..

Thanks, Nick
sql

Retrieving records within an index range, the nth record?

if I create an index for a table with some records, do you think I can retrieve records in a giving range? for example, the 5th to 10th records?

Possible? How can I do it?

When we insert data at the table, would the index in sequential order? How would the index be created for new inserted records?

I'm using SQL 2005 Express, not SQL 2000.if I create an index for a table with some records, do you think I can retrieve records in a giving range? for example, the 5th to 10th records?
Create index and schedule update statistics according to your requirement...

Use comparison operator for retrieving desired data.

i.e. Like, Between, Not Between etc.

When we insert data at the table, would the index in sequential order? How would the index be created for new inserted records?
Use clustered and non clustered index considering your needs.

Indexes are for arranging, sorting & fast retrieval of the data. Each time you don't need to create index when you insert a row, just schedule update statistics job or set auto update statistics.

Explore Books OnLine (From query analyzer -> Help Menu) for more information.|||how do we include index as a criteria when we use normal SQL query?|||how do we include index as a criteria when we use normal SQL query?
You don't need to do such thing, SQL Server will do it for you...|||after some research, i think it's easier for me to insert row_number() into the table instead of using index. What do you think?|||Read documents / books (rather get some knowledge) before making any changes...|||Data in a relational database has no inherent order.
Why do you think you need to add a rownumber column?

There are several ways to get a "page" or "range" of records from a table. Here is one:

select top 5 *
from
(select top 10 *
from [YourTable]
order by [YourColumn] asc) Subquery
order by [YourColumn] desc

You should not be relying on the concept of a "row number"|||this is for a particular case to generate rigid report using SQL 2005.

I need the output to be in the right order in my control, and because there is headers and footers involved, I got no choice but to fix them in certain special order.

the output is to an excel spreadsheet.|||So throw an ORDER BY clause into your query.

If you want the data to be ordered according to the way it was entered, then use a datetime column to record the entry date.|||Order by cannot work without row_number. I have too many identical rows.

Entry date is not accurate as the time unit used by SQL 2005 is not small enough.|||Then use an Identity column.|||unfortunately, there is no identity column, because I use this to generate a rigid report. the only identity column is the row number I created as part of the table.|||You're not listening...|||You can also use temporary table to process desired request in memory, rather to store in table permanently,
try just like this:

SELECT ROWID=IDENTITY(int,1,1) , Col1
INTO #TempTable FROM
<UrTable List and Where Clause>

and then retrieve from Temporary table, it will save ur time, disk space and locking issues on underlying table.

--Riaz

unfortunately, there is no identity column, because I use this to generate a rigid report. the only identity column is the row number I created as part of the table.|||it will save ur time, disk space and locking issues on underlying table.
Dunno about time but this will use more disk space than blindman's query (temp tables are not held in memory but written to tempdb) and will lock tempdb while it runs (this is due to the "select into" bit).

You can use the OVER clause if you are really eager to use row_number().

SELECT *
FROM--Derived TABLE - numbering rows
(SELECT *
, ROW_NUMBER() OVER (ORDERBY my_unique_column ASC) AS rn
FROM dbo.MyTable) AS der_t
WHERE rn BETWEEN 5 AND 10

Tuesday, March 20, 2012

Retrieving Last 'N' records from a Table in the Database

Hello House,

Please, I need the SQL statement/keyword used to Retrieve the Last 'N' records from a table in the Database; just as we have TOP 'N' for the First N-records in a table.

For example, ("Select TOP 'N' * From Particulars Order by Phone DESC", conn)

where N is the number of records to be retrieved.

I use both SQL Server 2005 and Microsoft Access.

Thanks.

Quote:

Originally Posted by Temidayo

Hello House,

Please, I need the SQL statement/keyword used to Retrieve the Last 'N' records from a table in the Database; just as we have TOP 'N' for the First N-records in a table.

For example, ("Select TOP 'N' * From Particulars Order by Phone DESC", conn)

where N is the number of records to be retrieved.

I use both SQL Server 2005 and Microsoft Access.

Thanks.


create an identity column on your table...select your table, ORDER BY (that identity column) DESC...the first record will be the last record inserted on your table

Retrieving last 12/24/36 hrs records

Hi there !!
I am new on this block. Can anyone help me to make sql queries which can retrieve last 12 hrs / last 24 hrs / last 36 hrs records.

I tried to make the logic for the last 3 hrs but yet not able to get the data which i want. I am using MS SQL Server 2000 and ASP.

My table named "campaign" contains the field 'camdate' which is of smalldatetime datatype.

Also, can i am able to retrieve the time from the same field (camdate)? if yes then how ??

Any suggestion is most welcome.

With Thankshi

SELECT *
FROM Table1
where DATEDIFF(hh, camdate, GETDATE()) >= 12

for last 12 hours

regards,
Gautam Vegad

Originally posted by sqlboy
Hi there !!
I am new on this block. Can anyone help me to make sql queries which can retrieve last 12 hrs / last 24 hrs / last 36 hrs records.

I tried to make the logic for the last 3 hrs but yet not able to get the data which i want. I am using MS SQL Server 2000 and ASP.

My table named "campaign" contains the field 'camdate' which is of smalldatetime datatype.

Also, can i am able to retrieve the time from the same field (camdate)? if yes then how ??

Any suggestion is most welcome.

With Thanks|||I think this will run faster, because it should only need to calculate dateadd(hh, -12, GETDATE()) once instead of calculating datediff for every record:

SELECT *
FROM Table1
where camdate >= dateadd(hh, -12, GETDATE())

Try it and see if the execution plan is different.

blindman|||Thanks to both of you..

Being a kid, i am not able to find the difference between dateadd and datediff. Can you put some light on it ? I shall be very greatful to you.|||Well, I ran one test on some data that I have, and the dateadd method was about 30% faster.

As I said, the difference is that the server calculates the result of dateadd once for the entire statement, while it must calculate the result of datediff once for every row.

blindman|||Well...maybe...

But the first one is a stage 2 predicate (non-sargable)..it'll have to do a table (or index) scan..

Blindman's has the ability to use an Index (stage 1, saragable)

And once you start talking volumes, the performance will be noticable...

MOO (well not really)|||Good point. I forgot about the sargableosityness of the two statements.

blindman

Monday, March 12, 2012

Retrieving Data from database

Hi,
I have relatively less experience to SQL. I had a question. Say I have to
display certain records on a datagrid. this datagrid is dependent on these
parameters.
suppose a user enters a partial value in a text box. eg: "12"
I make use of "like" feature(...partID like '12%') in the query and it
retrieved "3" records from the database.
using the resultset I have to retrieve 5 records prior and 5 records after
the "original" set of results(3)... and display the total records (5+3+5 = 13) on the datagrid.
whats the best way of doing this... I have no clue of how to do this... hope
I have conveyed my idea properly...
Place advice,
Stephen> using the resultset I have to retrieve 5 records prior and 5 records after
> the "original" set of results(3)... and display the total records (5+3+5 => 13) on the datagrid.
You need to define what "prior" and "after" mean. Perhaps you are used to
Excel or Access, but in SQL Server, a table is an unordered set of rows. To
obtain the 5 rows "before" and "after" a certain row, you need to tell us
how you determine which rows come before and after...
--
http://www.aspfaq.com/
(Reverse address to reply.)

Retrieving Data from database

Hi,
I have relatively less experience to SQL. I had a question. Say I have to
display certain records on a datagrid. this datagrid is dependent on these
parameters.
suppose a user enters a partial value in a text box. eg: "12"
I make use of "like" feature(...partID like '12%') in the query and it
retrieved "3" records from the database.
using the resultset I have to retrieve 5 records prior and 5 records after
the "original" set of results(3)... and display the total records (5+3+5 =
13) on the datagrid.
whats the best way of doing this... I have no clue of how to do this... hope
I have conveyed my idea properly...
Place advice,
Stephen
> using the resultset I have to retrieve 5 records prior and 5 records after
> the "original" set of results(3)... and display the total records (5+3+5 =
> 13) on the datagrid.
You need to define what "prior" and "after" mean. Perhaps you are used to
Excel or Access, but in SQL Server, a table is an unordered set of rows. To
obtain the 5 rows "before" and "after" a certain row, you need to tell us
how you determine which rows come before and after...
http://www.aspfaq.com/
(Reverse address to reply.)

Retrieving by months only

I have records in a table and 1 column is in the smalldatetime format which stores the date in the format "2004-09-22",2004-09-20",2004-09-12",2004-08-04" etc etc.

Can anyone tell me how to craft an SQL statement so that i can retrieve records for a certain month.For example,if i want to retrieve records for the month of September,i would get "2004-09-22",2004-09-20",2004-09-12" in results.SELECT * FROM yourTable WHERE
MONTH(ColumnName) = 9

Friday, March 9, 2012

Retrieving and Combining XML

I have a table in a SQL Server 2000 db that contains xml in one column.
I'd like to retrieve the xml from several records (10,000 actually) and
wrap them up into one xml document like this:
content of xmlData column:
<foo>
..
</foo>
Desired output:
<bar>
<foo>
..
</foo>
<foo>
..
</foo>
<foo>
..
</foo>
</bar>
I tried using FOR XML EXPLICIT, but that parsed all my tags to < and
>. How can I preserve the stored xml and output a single xml file
containing the stored xml for multiple records?
thanks
-ivan.FOR XML EXPLICIT was a good try. But you will need the !xml directive in
your column alias.
Eg,
select ... , xmlData as "element!1!row!xml" ... FOR XML EXPLICIT.
Best regards
Michael
"gilly3" <news@.NOSPAMgilly3.com> wrote in message
news:Xns96FBA3DBC554BnewsNOSPAMgilly3com
@.207.46.248.16...
>I have a table in a SQL Server 2000 db that contains xml in one column.
> I'd like to retrieve the xml from several records (10,000 actually) and
> wrap them up into one xml document like this:
> content of xmlData column:
> <foo>
> ...
> </foo>
> Desired output:
> <bar>
> <foo>
> ...
> </foo>
> <foo>
> ...
> </foo>
> <foo>
> ...
> </foo>
> </bar>
> I tried using FOR XML EXPLICIT, but that parsed all my tags to < and
> >. How can I preserve the stored xml and output a single xml file
> containing the stored xml for multiple records?
> thanks
> -ivan.|||"Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in
news:uZgb5Zq2FHA.3880@.TK2MSFTNGP12.phx.gbl:

> FOR XML EXPLICIT was a good try. But you will need the !xml directive
in
> your column alias.
> Eg,
> select ... , xmlData as "element!1!row!xml" ... FOR XML EXPLICIT.
> Best regards
> Michael
Thanks, that fixes my formatting problem, but I still had trouble
getting each record under a common root node.
My sql looked like this:
select
1 tag,
null parent,
[xmlData] [xRoot!1!xElement!xml]
from xmlTable
for xml explicit
this gave each record two parent nodes like this with no common root
node:
<xRoot>
<xElement>
<foo>
..
</foo>
</xElement>
</xRoot>
<xRoot>
<xElement>
<foo>
..
</foo>
</xElement>
</xRoot>
I want one parent node, and for that node to be the root of all the
records. I managed to make it work by adding a parent node in my
select, and eliminating extra nodes by using !xmltext, instead of !xml
like this:
select
1 tag,
null parent,
null [xRoot!1!!xmltext],
null [foo!2!!xmltext]
union all
select 2,
1,
null,
[xmlData]
from xmlTable
for xml explicit
This works, but it seems like a bit of a hack. Is there a more elegant
solution? If not, I'll just be happy this works as well as it does.
thanks
-ivan.|||In SQL Server 2005, you can use ROOT('myRoot') in the FOR XML clause.
In SQL Server 2000, your workaround works. Alternatively, there is a root
property on your connection that you can set in ADO, OLEDB, ADO.Net to get
the root element added on the client.
Best regards
Michael
"gilly3" <news@.NOSPAMgilly3.com> wrote in message
news:Xns96FCA5F95596AnewsNOSPAMgilly3com
@.207.46.248.16...
> "Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in
> news:uZgb5Zq2FHA.3880@.TK2MSFTNGP12.phx.gbl:
>
> in
> Thanks, that fixes my formatting problem, but I still had trouble
> getting each record under a common root node.
> My sql looked like this:
> select
> 1 tag,
> null parent,
> [xmlData] [xRoot!1!xElement!xml]
> from xmlTable
> for xml explicit
> this gave each record two parent nodes like this with no common root
> node:
> <xRoot>
> <xElement>
> <foo>
> ...
> </foo>
> </xElement>
> </xRoot>
> <xRoot>
> <xElement>
> <foo>
> ...
> </foo>
> </xElement>
> </xRoot>
> I want one parent node, and for that node to be the root of all the
> records. I managed to make it work by adding a parent node in my
> select, and eliminating extra nodes by using !xmltext, instead of !xml
> like this:
>
> select
> 1 tag,
> null parent,
> null [xRoot!1!!xmltext],
> null [foo!2!!xmltext]
> union all
> select 2,
> 1,
> null,
> [xmlData]
> from xmlTable
> for xml explicit
> This works, but it seems like a bit of a hack. Is there a more elegant
> solution? If not, I'll just be happy this works as well as it does.
> thanks
> -ivan.

Retrieving and Combining XML

I have a table in a SQL Server 2000 db that contains xml in one column.
I'd like to retrieve the xml from several records (10,000 actually) and
wrap them up into one xml document like this:
content of xmlData column:
<foo>
...
</foo>
Desired output:
<bar>
<foo>
...
</foo>
<foo>
...
</foo>
<foo>
...
</foo>
</bar>
I tried using FOR XML EXPLICIT, but that parsed all my tags to < and
>. How can I preserve the stored xml and output a single xml file
containing the stored xml for multiple records?
thanks
-ivan.
FOR XML EXPLICIT was a good try. But you will need the !xml directive in
your column alias.
Eg,
select ... , xmlData as "element!1!row!xml" ... FOR XML EXPLICIT.
Best regards
Michael
"gilly3" <news@.NOSPAMgilly3.com> wrote in message
news:Xns96FBA3DBC554BnewsNOSPAMgilly3com@.207.46.24 8.16...
>I have a table in a SQL Server 2000 db that contains xml in one column.
> I'd like to retrieve the xml from several records (10,000 actually) and
> wrap them up into one xml document like this:
> content of xmlData column:
> <foo>
> ...
> </foo>
> Desired output:
> <bar>
> <foo>
> ...
> </foo>
> <foo>
> ...
> </foo>
> <foo>
> ...
> </foo>
> </bar>
> I tried using FOR XML EXPLICIT, but that parsed all my tags to < and
> >. How can I preserve the stored xml and output a single xml file
> containing the stored xml for multiple records?
> thanks
> -ivan.
|||"Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in
news:uZgb5Zq2FHA.3880@.TK2MSFTNGP12.phx.gbl:

> FOR XML EXPLICIT was a good try. But you will need the !xml directive
in
> your column alias.
> Eg,
> select ... , xmlData as "element!1!row!xml" ... FOR XML EXPLICIT.
> Best regards
> Michael
Thanks, that fixes my formatting problem, but I still had trouble
getting each record under a common root node.
My sql looked like this:
select
1 tag,
null parent,
[xmlData] [xRoot!1!xElement!xml]
from xmlTable
for xml explicit
this gave each record two parent nodes like this with no common root
node:
<xRoot>
<xElement>
<foo>
...
</foo>
</xElement>
</xRoot>
<xRoot>
<xElement>
<foo>
...
</foo>
</xElement>
</xRoot>
I want one parent node, and for that node to be the root of all the
records. I managed to make it work by adding a parent node in my
select, and eliminating extra nodes by using !xmltext, instead of !xml
like this:
select
1 tag,
null parent,
null [xRoot!1!!xmltext],
null [foo!2!!xmltext]
union all
select 2,
1,
null,
[xmlData]
from xmlTable
for xml explicit
This works, but it seems like a bit of a hack. Is there a more elegant
solution? If not, I'll just be happy this works as well as it does.
thanks
-ivan.
|||In SQL Server 2005, you can use ROOT('myRoot') in the FOR XML clause.
In SQL Server 2000, your workaround works. Alternatively, there is a root
property on your connection that you can set in ADO, OLEDB, ADO.Net to get
the root element added on the client.
Best regards
Michael
"gilly3" <news@.NOSPAMgilly3.com> wrote in message
news:Xns96FCA5F95596AnewsNOSPAMgilly3com@.207.46.24 8.16...
> "Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in
> news:uZgb5Zq2FHA.3880@.TK2MSFTNGP12.phx.gbl:
> in
> Thanks, that fixes my formatting problem, but I still had trouble
> getting each record under a common root node.
> My sql looked like this:
> select
> 1 tag,
> null parent,
> [xmlData] [xRoot!1!xElement!xml]
> from xmlTable
> for xml explicit
> this gave each record two parent nodes like this with no common root
> node:
> <xRoot>
> <xElement>
> <foo>
> ...
> </foo>
> </xElement>
> </xRoot>
> <xRoot>
> <xElement>
> <foo>
> ...
> </foo>
> </xElement>
> </xRoot>
> I want one parent node, and for that node to be the root of all the
> records. I managed to make it work by adding a parent node in my
> select, and eliminating extra nodes by using !xmltext, instead of !xml
> like this:
>
> select
> 1 tag,
> null parent,
> null [xRoot!1!!xmltext],
> null [foo!2!!xmltext]
> union all
> select 2,
> 1,
> null,
> [xmlData]
> from xmlTable
> for xml explicit
> This works, but it seems like a bit of a hack. Is there a more elegant
> solution? If not, I'll just be happy this works as well as it does.
> thanks
> -ivan.

retrieving >1000 records from AD into Crystal

Hello all,

I am having a couple of problems selecting records from Active Directory. What I want to do is create a report that is grouped on a user object field in AD. Our users are not just contained with the 'Users' container, but also in other areas of the directory.

I've come across the problem that AD will only return the first 1000 records when you query it (mentioned here: http://support.businessobjects.com/library/kbase/articles/c2013533.asp). I believe you can get around this by somehow specifying the 'range' property, however I'm not 100% sure how to do this. This is my query as it stands:

Select displayName, ExtensionAttribute3, ExtensionAttribute2,
sAMAccountName, objectClass FROM 'LDAP://dc=blah,dc=blah2,dc=blah3,dc=blah4;;;Range=0-1000;subtree' WHERE objectClass='user'

Whenever I click OK to this I get the error "An invalid directory pathname was passed".

I guess I actually have 2 questions:
1. How do you get the range property to work (i.e. how can I return more than 1000 rows)
2. How can I get the query to search the subtrees of the directory (I think you need to specify the 'subtree' keyword, but again, this isn't working in my query.

Any help would be appreciated!
Cheers,
DanielIf you dont solve the problem search at http://support.businessobjects.com/

Wednesday, March 7, 2012

Retrieve records separated by spaces

Hello
I want to retrieve some records separated by spaces. Do you have any idea?
For example,
select col from T for xml path(''), root('x')
You get
<x>
<col>abc</col>
<col>def</col>
......
</x>
However I want to get,
<x>abc def ghi ... </x>
After post I got an idea, but looking for better one.
select @.x=(select col from T for xml path(''))
select @.x.query('
for $a in /col
return (concat(/$a/text(), " "))
')
for xml path
Any idea will be appreciated.
"Han" <hp4444@.kornet.net.korea> wrote in message
news:%233fljmVFHHA.4652@.TK2MSFTNGP04.phx.gbl...
> Hello
> I want to retrieve some records separated by spaces. Do you have any idea?
> For example,
> select col from T for xml path(''), root('x')
> You get
> <x>
> <col>abc</col>
> <col>def</col>
> .....
> </x>
> However I want to get,
> <x>abc def ghi ... </x>
>
|||This should be more elegant and performing (not tested - from memory)
select col as "data()" from T for xml path(''), root('x')
Best regards,
Eugene
"Han" <hp4444@.kornet.net.korea> wrote in message
news:%23aSIkxVFHHA.2268@.TK2MSFTNGP06.phx.gbl...
> After post I got an idea, but looking for better one.
> select @.x=(select col from T for xml path(''))
> select @.x.query('
> for $a in /col
> return (concat(/$a/text(), " "))
> ')
> for xml path
> Any idea will be appreciated.
> "Han" <hp4444@.kornet.net.korea> wrote in message
> news:%233fljmVFHHA.4652@.TK2MSFTNGP04.phx.gbl...
>
|||Thanks Eugene.
It worked.
"Eugene Kogan [MSFT]" <eugene.kogan@.online.microsoft.com> wrote in message
news:upkjKm$HHHA.4068@.TK2MSFTNGP03.phx.gbl...
> This should be more elegant and performing (not tested - from memory)
> select col as "data()" from T for xml path(''), root('x')
> Best regards,
> Eugene
> "Han" <hp4444@.kornet.net.korea> wrote in message
> news:%23aSIkxVFHHA.2268@.TK2MSFTNGP06.phx.gbl...
>