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

Friday, March 30, 2012

Role design issue

I have a strange roles problem.

Is there a way we can accomplish this:

Say, the fact table has 100 records. each record having a new account number (100 accounts in 100 records).

The problem is we have users who have to see only some accounts. For example, user 1 has to see only accounts 1-10, user 2 has to see only accounts 11-20, user 3 has to see only accounts 21-30. and so on...

I know we can create different roles and create perspectives for these roles, but the problem is the list that defines what they can see is a table of 1000 user entries, each row has its own conditions for each user type. (Actually, each condition is a combination of different dimensions. For example, user 1 has to see account 1-10 and products A-D)

Does anyone have any idea on how to do this?

Thanks in advance

Luckily the problem you describe is very common. So common it has it's own name, it is oftenly referred as "Dynamic Dimension Security".

There are quite a few articles about it. Here is one for you http://sqljunkies.com/WebLog/mosha/archive/2004/12/16/5605.aspx

Search for it, you will find quite a bit information.

Edward Melomed.
--
This posting is provided "AS IS" with no warranties, and confers no rights.

|||Thanks Edward, I looked at it and I think thats what am looking for. will come back for your help if I cant figure something out :-)

Friday, March 23, 2012

Right Question?

Hi Group,
I have a question in SQL Server 2000.
The question is, I have a table with 2 millions of records and I want
to fetch the record from 200 to 400 rows and the table doesn't content
any identity cols nor any numeric col all the varchar field. Can you
put some light on it?
Regards
ArijitHi
http://www.aspfaq.com/show.asp?id=2120
<arijitchatterjee123@.yahoo.co.in> wrote in message
news:1154433609.267834.40780@.h48g2000cwc.googlegroups.com...
> Hi Group,
> I have a question in SQL Server 2000.
> The question is, I have a table with 2 millions of records and I want
> to fetch the record from 200 to 400 rows and the table doesn't content
> any identity cols nor any numeric col all the varchar field. Can you
> put some light on it?
> Regards
> Arijit
>|||Hi
To get a number of records in a range you need to be able to order them!!!
Check out http://www.aspfaq.com/show.asp?id=2120 for various techniques that
can be used on SQLServer 7.0 and 2000. For SQL Server 2005 check out the new
ranking and TOP functionality.
John
"arijitchatterjee123@.yahoo.co.in" wrote:

> Hi Group,
> I have a question in SQL Server 2000.
> The question is, I have a table with 2 millions of records and I want
> to fetch the record from 200 to 400 rows and the table doesn't content
> any identity cols nor any numeric col all the varchar field. Can you
> put some light on it?
> Regards
> Arijit
>

Right Question?

Hi Group,
I have a question in SQL Server 2000.
The question is, I have a table with 2 millions of records and I want
to fetch the record from 200 to 400 rows and the table doesn't content
any identity cols nor any numeric col all the varchar field. Can you
put some light on it?
Regards
ArijitHi
http://www.aspfaq.com/show.asp?id=2120
<arijitchatterjee123@.yahoo.co.in> wrote in message
news:1154433609.267834.40780@.h48g2000cwc.googlegroups.com...
> Hi Group,
> I have a question in SQL Server 2000.
> The question is, I have a table with 2 millions of records and I want
> to fetch the record from 200 to 400 rows and the table doesn't content
> any identity cols nor any numeric col all the varchar field. Can you
> put some light on it?
> Regards
> Arijit
>|||Hi
To get a number of records in a range you need to be able to order them!!!
Check out http://www.aspfaq.com/show.asp?id=2120 for various techniques that
can be used on SQLServer 7.0 and 2000. For SQL Server 2005 check out the new
ranking and TOP functionality.
John
"arijitchatterjee123@.yahoo.co.in" wrote:
> Hi Group,
> I have a question in SQL Server 2000.
> The question is, I have a table with 2 millions of records and I want
> to fetch the record from 200 to 400 rows and the table doesn't content
> any identity cols nor any numeric col all the varchar field. Can you
> put some light on it?
> Regards
> Arijit
>

Wednesday, March 21, 2012

RFC: Trigger uodating records in INSERTED Table

1) We have a trigger which applies further changes to the inserted/updated
records. Is this fundamentally bad or an acceptable practice?
2) We suspect that one version of such a trigger is causing deadlocks.
Interestingly this does not seem to happen if we use a cursor. See two
versions below. Any insights why the behavior differs?
Looking forward to your comments,
Jonathan Orgel
-- Suspected of causing dead lock
CREATE TRIGGER IU_DOCUMENTS ON DOCUMENTS
FOR INSERT, UPDATE
AS
BEGIN
UPDATE DOCUMENTS SET X=Y WHERE DOCUMENTID IN (SELECT DOCUMENTID FROM
INSERTED)
END
-- OK...
CREATE TRIGGER IU_DOCUMENTS ON DOCUMENTS
FOR INSERT, UPDATE
AS
BEGIN
DECLARE IndexCursor CURSOR LOCAL STATIC FOR SELECT DOCUMENTID FROM
INSERTED
OPEN IndexCursor
FETCH NEXT FROM IndexCursor INTO @.DOCUMENTID
WHILE @.@.FETCH_STATUS = 0
BEGIN
UPDATE DOCUMENTS SET X=Y WHERE DOCUMENTID = @.DOCUMENTID
FETCH NEXT FROM IndexCursor INTO @.DOCUMENTID
END
CLOSE IndexCursor
DEALLOCATE IndexCursor
ENDRewrite your first trigger to be like the following
CREATE TRIGGER IU_DOCUMENTS ON DOCUMENTS
FOR INSERT, UPDATE
AS
BEGIN
UPDATE
a
SET
X=Y
from
documents a inner join inserted b on
a.documentid=b.documentid
END
I think you are getting deadlocks because of "where documentid in ..."
syntax. Usually this causes SQL Server not to use index optimisation, and
would attempt to do a table scan. Since your code is also doing an update on
the same table, this would cause deadlocks. Also make sure you have an index
on documentid. By the look of things, documentid should be the primary key
and should obviously have been indexed to start with.
HTH
"Jonathan Orgel" <Jonathan@.srssoft.com> wrote in message
news:ek1TflmUGHA.1728@.TK2MSFTNGP11.phx.gbl...
> 1) We have a trigger which applies further changes to the inserted/updated
> records. Is this fundamentally bad or an acceptable practice?
> 2) We suspect that one version of such a trigger is causing deadlocks.
> Interestingly this does not seem to happen if we use a cursor. See two
> versions below. Any insights why the behavior differs?
> Looking forward to your comments,
> Jonathan Orgel
> -- Suspected of causing dead lock
> CREATE TRIGGER IU_DOCUMENTS ON DOCUMENTS
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE DOCUMENTS SET X=Y WHERE DOCUMENTID IN (SELECT DOCUMENTID FROM
> INSERTED)
> END
> -- OK...
> CREATE TRIGGER IU_DOCUMENTS ON DOCUMENTS
> FOR INSERT, UPDATE
> AS
> BEGIN
> DECLARE IndexCursor CURSOR LOCAL STATIC FOR SELECT DOCUMENTID FROM
> INSERTED
> OPEN IndexCursor
> FETCH NEXT FROM IndexCursor INTO @.DOCUMENTID
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> UPDATE DOCUMENTS SET X=Y WHERE DOCUMENTID = @.DOCUMENTID
> FETCH NEXT FROM IndexCursor INTO @.DOCUMENTID
> END
> CLOSE IndexCursor
> DEALLOCATE IndexCursor
> END
>
>

Rewriting left joins

Hello,

I am working on a query that has 11 left join statements, some are hitting against reference data that has a small amount of records, whereas others not so small. From a performance standpoint, should I look at rewriting this query, and how would I do so? What is an alternative to left joins; any examples anyone has?

Thanks.

The alternative to a join is a subquery. Google "Join or subquery" for information in which performs better. Loads of different opinions, but it would appear that only testingyourquery inyourenvironment will produce the right answer foryou.|||

bmains:

From a performance standpoint, should I look at rewriting this query

I would say that it depends on whether your query is performing poorly or not. I wouldn't touch it if it isn't broken

Monday, March 12, 2012

Re-using Identity achieved after INSERT query

Hi all,
I'm using an INSERT query to add records to a table with a defined
Identity column.
The query looks like this:
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT SCOPE_IDENTITY();
The return value is Text_ID, and I'm using the it for another insert
query:
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
SELECT SCOPE_IDENTITY();
Is there a way to combine the two queries into a single query ?
Something like this:
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT SCOPE_IDENTITY() = Text_ID;
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
SELECT SCOPE_IDENTITY();
Thanks to all.You can use variable for this.
Declare @.TextID int
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',9,1);
SELECT @.TextID = SCOPE_IDENTITY();
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,@.TextID ,1);
...
MC
"Avital" <avital.chissick@.gmail.com> wrote in message
news:1193566518.353471.43280@.v3g2000hsg.googlegroups.com...
> Hi all,
> I'm using an INSERT query to add records to a table with a defined
> Identity column.
> The query looks like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY();
> The return value is Text_ID, and I'm using the it for another insert
> query:
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Is there a way to combine the two queries into a single query ?
> Something like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY() = Text_ID;
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Thanks to all.
>|||I think you just need to use a variable:
DECLARE @.TextId INT
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT @.TextId = SCOPE_IDENTITY();
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,@.Text_ID,1);
SELECT SCOPE_IDENTITY();
Adam Machanic
SQL Server MVP - http://sqlblog.com
Author, "Expert SQL Server 2005 Development"
http://www.apress.com/book/bookDisplay.html?bID=10220
"Avital" <avital.chissick@.gmail.com> wrote in message
news:1193566518.353471.43280@.v3g2000hsg.googlegroups.com...
> Hi all,
> I'm using an INSERT query to add records to a table with a defined
> Identity column.
> The query looks like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY();
> The return value is Text_ID, and I'm using the it for another insert
> query:
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Is there a way to combine the two queries into a single query ?
> Something like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY() = Text_ID;
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Thanks to all.
>

Wednesday, March 7, 2012

returning value from sql to c#

hello,
I have a small problem. i'm adding records into the DB. the primary keyis the company name which is abviously unique. before saving the recordi check in the stored procedure if the company code is unique or not.if unique then the record is added & an output parameter is set to2 & should b returned to the data access layer. if not unique then3 should be returned. but everytime it seems to be returning 2 whetherit is unique or not. can u plz help me? here is the code of the dataaccess layer:
cmd.Parameters.Add("@.Status", SqlDbType.Int);
cmd.Parameters["@.Status"].Value = ParameterDirection.ReturnValue;

//cmd.UpdatedRowSource = UpdatedRowSource.OutputParameters;
cmd.ExecuteNonQuery();
status = (int)cmd.Parameters["@.Status"].Value;

here is the stored procedure:
CREATE PROCEDURE spOrganizationAdd(
@.OrgCode varchar(10),
@.OrgName varchar(50),
@.AddressLine1 varchar(30),
@.AddressLine2 varchar(30),
@.City varchar(15),
@.State varchar(15),
@.Country varchar(15),
@.PinCode varchar(7),
@.Phone varchar(20),
@.Fax varchar(20),
@.Website varchar(30),
@.Email varchar(50),
@.CreatedBy int,
@.LastModifiedBy int,
@.Status INTEGER OUTPUT) AS
BEGIN TRAN
IF EXISTS(SELECT OrgCode FROM tblOrganizationMaster WHERE OrgCode = @.OrgCode)
BEGIN
SET @.Status = 3

END
ELSE
BEGIN
INSERT INTO tblOrganizationMaster VALUES(
@.OrgCode,
@.OrgName,
@.AddressLine1 ,
@.AddressLine2 ,
@.City ,
@.State,
@.Country,
@.PinCode,
@.Phone,
@.Fax ,
@.Website,
@.Email,
@.CreatedBy ,
GETDATE(),
@.LastModifiedBy ,
GETDATE())
SET @.Status = 2
END
IF @.@.ERROR = 0 COMMIT TRAN
ELSE ROLLBACK TRAN

plz reply as soon as possible.

Change this:

cmd.Parameters.Add("@.Status", SqlDbType.Int);
cmd.Parameters["@.Status"].Value = ParameterDirection.ReturnValue;

To this:

cmd.Parameters.Add("@.Status", SqlDbType.Int);
cmd.Parameters["@.Status"].Direction = ParameterDirection.Output;

and then it should work.

Bill

Returning the entered date

My question might be stupid but How to retrieve records for a date that I would like to determine?

Means I would like to have a parameter where I can enter the date I want to retrieve my records.

At the beginning I had it set up as: Between [Beginning Date] And [Ending Date]. Now I just want One parameter

Thanks for your helpHi
I am not sure if I fully understand your question.
you could do something like

select orderid, ordername from ordertable where dt_ordered = to_date('DATE_REQUIRED','YYYY/MM/DD');

Make sure DATE REQUIRED is of the format 'YYYY/MM/DD'.
Thanx and Regards
Aruneesh|||I want SQL to retrieve all the records to the corresponding date that I'll enter.

Means I'll have one pop up parameter where I enter the date I want.

I have a already one pop up parameter in my SQL statement for country which is: Like [Country:].
When I run my query a parameter pop up and I return the country I want.

I would like to do the same thing with the Date. Having a parameter where I enter the date I want.

Thanks|||I wanted to get some clarification on the scenario.
I dont under what popup you are mentioning here.

Are you anyway using VB to link it to some DB.
Please clarify the popup portion.
Thanx and Regards
Aruneesh|||The pop portion is just a parameter that pops up when you run your query.

In access your query can be presented in 3 ways: Design View, Table View and SQL view.

I'm working out of the Design view and when you specify a parameter in the criteria part of a field, it will pop up as a parameter when you run your Table view.

Anyway I found the solution. For the date and to return the date that you want on your parameter you just set the criteria as this:
Like [Date:] in your date field. In SQL it's translated like this:
WHERE Table.OrderDate = [Date:]

And now I bumped into another issue:
How to return the text that I want in my parameter. Means I want to look for a word in the whole title and the query will run the companies that contain that word.
I don't want to specify the word in my SQL statement I want to leave it open like I've done above for the date. (I'm working out of Access Database)

Thanks for the help

Saturday, February 25, 2012

Returning small managable sets from a SELECT statement

I have a Database that contains 10,000 records. I execute a SELECT statement that returns 8000. I need those 8000 and cannot refine my statement to return a smaller subset.

My problem is I don't want all the results back in one go. I would like to return to 1000 rows on my first call. On my second call I would like another 1000 rows starting from the end of the last call and so on...

Is this possible? Also the table has no unique key either, and that ain't gonna change.

Any suggestions. I would like to implement this in SQL.

Thanks in advance to anyone who comes up with a good solutionHello,

you can use PL/SQL to open a cursor an fetch the records block wise ..

Use

OPEN, FETCH and CLOSE statements to create a package and use this in your application.

Hope that hint helps ?

Manfred Peter
(Alligator Company GmbH)
http://www.alligatorsql.de

Returning range of records in MSSQL

Hi guys, I need to know if there is a way to select a range of records from a database. Kind of like using SELECT TOP 1000, but I need to be able to specify which records to return. So I imagine it would look like this:

SELECT TOP 2000-5000 * FROM customers WHERE groupid=2 ORDER BY FirstName DESC

Where this statement would return only records 2000 to 5000 of the returned results.Did you try reading the manual?

Not found it?

Reason: no, there is no way to do this.

Sorry.|||Well, you *could* do something like this, although I suggest you check the performance.


SELECT
*
FROM
(
SELECT TOP 3001
*
FROM
(
SELECT TOP 5000
*
FROM
customers
WHERE
groupid = 2
ORDER BY
FirstName DESC
) AS S1
ORDER BY
FirstName ASC
) AS S2
ORDER BY
FirstName DESC

Terri

Returning Range of Records from SQL Server 7 - Old issue revisited

Hi all,

I am using the following stored procedure in SQL 7 to return a range of records.


CREATE PROCEDURE spRetMyTable
@.maxRows int, @.lastRecord int, @.SortPhrase varchar(122)
AS
begin
DECLARE @.stSql VARCHAR(255)
SET ROWCOUNT @.maxRows
SET @.stSql = 'SELECT * FROM (SELECT TOP 10 colPrimary, col1, col2, col3 FROM (SELECT TOP ' + CONVERT(VARCHAR, @.lastRecord) +
'colPrimary, col1, col2, col3 FROM [MyTable] ORDER BY [colPrimary] ASC) AS tbl1 ORDER BY [colPrimary] DESC) AS tbl2 ORDER by [colPrimary] ASC'
exec(@.stSql)
set rowcount 0
end

To execute the above procedure I am issuing the command:

execute spRetMyTable @.maxRows 10, @.lastRecord 1500

The column [colPrimary] is the primary field in the table.

I will be using the selected records in a gridView with paging (3 records per page). So if the next page is selected I would require to take out record 1491 to record 1494 and Add record 1501 to record 1503 in the datatable subject to the availability of records in the table MyTable.

How do I provide sorting by col1, col2 or col3? It could be single column or multiple column sorting as chosen by the user during runtime.


Is there any performance overhead in the above method in the first place?
Could it be improved by any alternative process?

I need YOUR ASSISTANCE to cater to the above issues in a feasible way.

Thanks in advance.

You may take a look atSorting Data with Data Source Controls

|||

HiIori_Jay,

Thanks. I will try on the advised line.

Returning random records and NOT similar (random questions)

Hi,

I need to extract randomly 5 records from the table "Questions". Now I use

SELECT TOP 5 FROM Questions ORDERBY NEWID()

And it works. The problem is that I need an additional thing: if SQL
extracts record with ID=4, then it should not extract record with ID=9,
because they are similar. I mean, I'd like something to tell SQL that if it
extracts some questions, then it SHOULD NOT extract other ones.

How can I do it?

Thanks!

Luke"Luke" <nospam@.nospam.com> wrote in message news:<%ejcc.18367$hc5.868453@.news3.tin.it>...
> Hi,
> I need to extract randomly 5 records from the table "Questions". Now I use
> SELECT TOP 5 FROM Questions ORDERBY NEWID()
> And it works. The problem is that I need an additional thing: if SQL
> extracts record with ID=4, then it should not extract record with ID=9,
> because they are similar. I mean, I'd like something to tell SQL that if it
> extracts some questions, then it SHOULD NOT extract other ones.
> How can I do it?
> Thanks!
> Luke

You need to define some logic to say why 4 and 9 are "similar". For
example, should ABS(x-y) > 10 be true for all possible combinations of
numbers in the result set? Or since you're retrieving questions,
perhaps they're in groups, ie. questions 1-20 are on the same topic,
21-40 on a different topic etc., and you want only one random question
from each topic?

Depending on what logic you decide, you might want to consider doing
this in a client application - if the first value you retrieve affects
which ones you can retrieve later, then a cursor-based solution might
be the only way to do it on the server side, and that will be slow. It
may be faster to use a client app which retrieves the maximum and
minimum values (or whatever data you need to reference in your logic),
and then applies your pseudo-random algorithm.

Simon

returning random records

I need to select a list of random records from a table.
The table has a numeric ID column that is a primary key (identity
property). I would like to return a set of 1000 records where the only
criteria is a random ID number.
I can come up with a cursor solution that does what I need but is there a
set-based solution to the problem?
What is the most efficient way to return say 1000 random records from a
table?Try:
select top 1000
*
from
MyTable
order by
newid()
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
"Dave" <Dave@.discussions.microsoft.com> wrote in message
news:25157515-DC71-4A34-B4C5-EE30FBD1E234@.microsoft.com...
>I need to select a list of random records from a table.
> The table has a numeric ID column that is a primary key (identity
> property). I would like to return a set of 1000 records where the only
> criteria is a random ID number.
> I can come up with a cursor solution that does what I need but is there a
> set-based solution to the problem?
> What is the most efficient way to return say 1000 random records from a
> table?
>
>|||Dave
You need to perfrom
SELECT TOP 1000 *
FROM table
ORDER BY NEWID()
as per the example below:
CREATE TABLE foo
(
i INT
)
SET NOCOUNT OFF
DECLARE @.maxVal BIGINT
DECLARE @.i BIGINT
SET @.maxVal = 10000
SET @.i = 1
BEGIN TRAN
INSERT INTO foo VALUES(1)
WHILE @.i * 2 <= @.maxVal
BEGIN
INSERT INTO foo
SELECT i + @.i FROM foo
SET @.i = @.i * 2
END
INSERT INTO foo
SELECT i + @.i FROM foo
WHERE i + @.i <= @.maxVal
COMMIT TRAN
SELECT TOP 1000 *
FROM foo
ORDER BY NEWID()
- Peter Ward
WARDY IT Solutions
"Dave" wrote:

> I need to select a list of random records from a table.
> The table has a numeric ID column that is a primary key (identity
> property). I would like to return a set of 1000 records where the only
> criteria is a random ID number.
> I can come up with a cursor solution that does what I need but is there a
> set-based solution to the problem?
> What is the most efficient way to return say 1000 random records from a
> table?
>
>|||Hey that will not give randon records but same kind of records everytime as
top uses the same logic( it may be same order)
so you have some thing called RAND function. see books online for that. You
have to do little bit of work to achive the results using rand function. see
books online for that.
Regards
R.D
--Knowledge gets doubled when shared
"P. Ward" wrote:
> Dave
> You need to perfrom
> SELECT TOP 1000 *
> FROM table
> ORDER BY NEWID()
> as per the example below:
>
> CREATE TABLE foo
> (
> i INT
> )
>
> SET NOCOUNT OFF
> DECLARE @.maxVal BIGINT
> DECLARE @.i BIGINT
> SET @.maxVal = 10000
> SET @.i = 1
> BEGIN TRAN
> INSERT INTO foo VALUES(1)
> WHILE @.i * 2 <= @.maxVal
> BEGIN
> INSERT INTO foo
> SELECT i + @.i FROM foo
> SET @.i = @.i * 2
> END
> INSERT INTO foo
> SELECT i + @.i FROM foo
> WHERE i + @.i <= @.maxVal
> COMMIT TRAN
>
> SELECT TOP 1000 *
> FROM foo
> ORDER BY NEWID()
>
> - Peter Ward
> WARDY IT Solutions
>
> "Dave" wrote:
>|||Dave
This should solve your problem: Read this article
http://msdn.microsoft.com/library/d...r />
p04c1.asp
--
Regards
R.D
--Knowledge gets doubled when shared
"Dave" wrote:

> I need to select a list of random records from a table.
> The table has a numeric ID column that is a primary key (identity
> property). I would like to return a set of 1000 records where the only
> criteria is a random ID number.
> I can come up with a cursor solution that does what I need but is there a
> set-based solution to the problem?
> What is the most efficient way to return say 1000 random records from a
> table?
>
>|||On Mon, 7 Nov 2005 21:19:15 -0800, R.D wrote:

>Hey that will not give randon records but same kind of records everytime as
>top uses the same logic( it may be same order)
Hi R.D.,
You're incorrect. This WILL give random rows.
The TOP is executed in conjunction with the ORDER BY. So before applying
the TOP, SQL Server will first order all rows. NEWID() is called for
each row; this results in a semi-random (*) value. The rows are then
ordered by this semi-random value, resulting in a semi-random order.
Then, the TOP 1000 of those semi-randoomly ordered rows are returned.
Try executing the following in Nirthwind:
SELECT TOP 5 * FROM Customers
ORDER BY NEWID()
SELECT TOP 5 * FROM Customers
ORDER BY NEWID()
SELECT TOP 5 * FROM Customers
ORDER BY NEWID()
(*) The generator for NEWID's is not designed to be a good random number
generator, but it's close enoguh for most practical purposes. I wouldn't
use it for serious gambling-strategy analysis or for the 15 million
dollar draw, but for getting random samples out of a table, it's
certainly good enough.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||The first problem is that there are two kinds of random selection from
a set:
1) With replacement = you can get multiple copies of the same value.
This is shooting dice.
This one is easy if you have a random function in your SQL product.
Most of the pseudo-random generators return a floating point fraction
value between 0.00 and 0.9999... at whatever precision your SQL engine
has. The choice of a seed to start the generator can be the system
clock or some other constantly changing value.
SELECT S1.key_col
FROM SomeTable AS S1, SomeTable AS S2
WHERE S1.key_col <= S2.key_col
GROUP BY S1.key_col
HAVING COUNT(S2.key_col)
= (SELECT COUNT(*)
FROM SomeTable AS S3) * RANDOM(seed) + 1.0;
Or you can add a column for this in SQL Server (but not Oracle).
CREATE TABLE RandNbrs2
(seq_nbr INTEGER PRIMARY KEY,
randomizer FLOAT -- warning !! not standard SQL
DEFAULT (
(CASE (CAST(RAND() + 0.5 AS INTEGER) * -1)
WHEN 0.0 THEN 1.0 ELSE -1.0 END)
* (CAST(RAND() * 100000 AS INTEGER) % 10000)
* RAND())
NOT NULL);
INSERT INTO RandNbrs2 VALUES (1, DEFAULT);
INSERT INTO RandNbrs2 VALUES (2, DEFAULT);
INSERT INTO RandNbrs2 VALUES (3, DEFAULT);
INSERT INTO RandNbrs2 VALUES (4, DEFAULT);
INSERT INTO RandNbrs2 VALUES (5, DEFAULT);
INSERT INTO RandNbrs2 VALUES (6, DEFAULT);
INSERT INTO RandNbrs2 VALUES (7, DEFAULT);
INSERT INTO RandNbrs2 VALUES (8, DEFAULT);
INSERT INTO RandNbrs2 VALUES (9, DEFAULT);
INSERT INTO RandNbrs2 VALUES (10, DEFAULT);
2) Without replacement = you can each value only once. This is dealing
playing cards.
This is trickier. I would start with a table that has the keys and a
sequentially numbered column in it:
CREATE TABLE CardDeck
(keycol <datatype> NOT NULL PRIMARY KEY,
seq INTEGER NOT NULL);
INSERT INTO CardDeck (keycol, seq)
SELECT S1.keycol, COUNT(S2.keycol)
FROM SomeTable AS S1, Sometable AS S2
WHERE S1.key_col <= S2.key_col
GROUP BY S1.key_col;
Now shuffle the deck by determing a random swap pair for all the rows.
Somethign like this in SQL/PSM
BEGIN
DECLARE i INTEGER, j INTEGER;
SET i = (SELECT COUNT(*) FROM CardDeck);
WHILE i < 0
LOOP
SET j = (SELECT COUNT(*) FROM CardDeck) * RANDOM(seed) + 1.0;
UPDATE CardDeck
SET seq = CASE WHEN seq = i THEN j
WHEN seq = j THEN i
ELSE seq END;
WHERE seq IN (i, j);
SET i = i - 1;
LOOP END;
END;
You don't really need j, but it makes the code easier to read.
Biography:
Marsaglia, G and Zaman, A. 1990. Toward a Univesal Random Number
Generator.
Statistics & Probability Letters 8 (1990) 35-39.
Marsaglia, G, B. Narasimhan, and A. Zaman. 1990. A Random Number
Generator for
PC's. Computer Physics Communications 60 (1990) 345-349.
Leva, Joseph L. 1992. A Fast Normal Random Number Generator. ACM
Transactions
on Mathematical Software. Dec 01 1992 v 18 n 4. p 449
Leva, Joseph L. 1992. Algorithm 712: A Normal Random Number Generator.
ACM
Transactions on Mathematical Software. Dec 01 1992 v 18 n 4. p 454
Bays, Carter and W.E. Sharp. 1992. Improved Random Numbers for Your
Personal
Computer or Workstation. Geobyte. Apr 01 1992 v7 n2. p 25
Hulquist, Paul F. 1991. A Good Random Number Generator for
Microcomputers.
Simulation. Oct 01 1991 v57 n 4. p 258
Komo, John J. 1991. Decimal Pseudo-random Number Generator. Simulation.
Oct 01
1991 v57 n4. p 228
Chambers, W.G. and Z.D. Dai. 1991. Simple but Effective Modification to
a
Multiplicative Congruential Random-number Generator. IEEE Proceedings.
Computers and Digital Technology. May 01 1991 v 138 n3. p 121
Maier, W.L. 1991.. A Fast Pseudo Random Number Generator. Dr. Dobb's
Journal.
May 01 1991 v17 n 5. p 152
Sezgin, Fatin. 1990. On a Fast and Portable Uniform Quasi-random Number
Generator. Simulation Digest. Wint 1990 v 21 n 2. p 30
Macomber, James H. and Charles S. White. 1990. An n-Dimensional Uniform
Random
Number Generator Suitible for IBM-Compatible Microcomputers.
Interfaces. May 01
1990 v 20 n 3. p 49
Carta, David G. 1990. Two Fast Implementations of the "Minimal
Standard"
Random Number Generator. Communications of the ACM. Jan 01 1990 v 33 n
1. p
87
Elkins, T.A. 1989. A Highly Random-number Generator. Computer
Language. Dec
01 1989 v 6 n 12 p 59
Kao, Chiang. A Random Number Generator for Microcomputers. OR: The
Journal of
the Operational Research Society. Jul 01 1989 v 40 n 7. p 687
Chassing, P. 1989. An Optimal Random Number Generator Zp. Statistics &
Probability Letters. Feb 01 1989 v 7 n 4. p 307
Also, you can contact Kenneth G. Hamilton 72727,177 who has done some
work
with RNG's. He has implemented one (at least one) of the best.
"A Digital Dissolve for Bit-Mapped Graphics Screens" by Mike Morton in
Dr.
Dobb's Journal, November 1986, page 48.
CMOS Cookbook by Don Lancaster; Sams 1977, page 318.
Art of Computer Programming, Volume 2: Seminumeral Algorithms, 2nd
edition by
Donald Knuth; Addison-Wesley 1981; page 29.
Numerical Recipes in Pascal: The Art of Scientific Computing by Press
et al.;
Cambridge 1989; page 233.

returning part of recordset

Hi, I have a table that has the following field and results.

I want a where clause that returns records that start 0000......

I need to exclude those records that start 0001........

Can anyone help

oseq
---
0000
0000.0000
0000.0000.0000
0000.0000.0000.0000
0000.0000.0000.0000.0000
0000.0000.0000.0000.0001
0000.0000.0000.0001
0000.0000.0001
0001
0001.0000
0001.0001
0001.0002
0000.0000.0002
0000.0000.0003
0000.0001
0000.0001.0000
0000.0001.0000.0000
0000.0001.0000.0000.0000
0000.0001.0000.0000.0000.0000
0000.0026.0004.0009
0000.0026.0004.0010You could use either the substring function or the like operator. Check BOL for more detail.

Tom|||Try like this

select * from test
where oseq like '0000%'

Roshmi Choudhury|||Roshmi's answer is simpler, and potentially much more efficient because it allows the query to use an index.

-PatP

Tuesday, February 21, 2012

Returning more than one Record from SP...

Hi ,
Is there a way in SQL Server stored procedure to return multiple records/ more than one records...?
Thanks in Advance...
-Mohit.Do you mean as output to another stored procedure? (Of course they can return more than one record...)

Consider using a User-defined table function. These can return datasets that can be directly joined in sql statements as if they were actual tables.

Returning Matching/Non matching Records

Hi All

I have a strange request that might not be possible based on the laws of relational databases but I thought I'd give it a try.

I have three tables which for simplicity I will call A, B and C. Table A contains my master records, Table B contains user details and the final table contains some extra data

In my initial search when joining A and B, I return 100 records. I then need to search in table C for these 100 records based on a criteria. the expected result should return all 100 rows for the ones that match and also the ones that do not match. The problem is that in Table C, not all the 100 IDs exist, so there will not be a corresponding record. Unfortunately, our users still want to see all 100 records in the output. Is this possible

As always any help or direction would be appreciated.read brett's sticky...

ddl? sample data? do you have some code already?|||Is this possibleyou betcha!!

hint: A inner join B left outer join C|||it's possible, study more on the left join right join and inner join :)|||Thanks for the responses guys. I was actually doing this on behalf of a friend who I was awaiting some ddl from. He now reports that he's been able to resolve his issue. Thanks.|||Someone correct my method please...

I would have created 2 queries - one with IN and the other using a NOT IN criteria...

then unioned them...

If you get me

returning limited number of records!

I am using ORDER BY NEWID() to return random record from sql database. how do i go about returning only 5 random records instead of all records.

Thanks.Since SELECT * FROM Table ORDER BY NEWID() will return the rows in a random order, all you need to do is use the TOP keyword to limit the results for that particular query.

SELECT TOP 5 * FROM Table
ORDER BY NEWID()

If, for some reason, that doesn't work, there's the slightly less elegant solution of

SET ROWCOUNT = 5
SELECT * FROM Table
ORDER BY NEWID()
SET ROWCOUNT = 0

I hope this helps.|||it's working perfect.

thanks.

Returning Duplicate Records

I have a Transactions table w/the following columns (all VarChar):
CustomerID,
Customer_Name,
User_Name
And and Admin table w/the following columns (VarChar):
User_Name,
Company_ID
Now I want to return any records where the CustomerID is duplicated for
different Customer_Names when Grouped by Company_ID. Here's a sample of wha
t
the returned data will look like:
Company_ID Customer_ID Customer_Name
R9 321 Ted Smith
R9 321 Rob Wand
Here's my query:
SELECT COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME,
COUNT (CUSTOMER_ID) AS NUM_OCCUR
FROM TRANSACTIONS
INNER JOIN ADMIN ON
ADMIN.USER_NAME = TRANSACTIONS.USER_NAME
GROUP BY COMPANY_ID, CUSTOMER_NAME, CUSTOMER_ID
HAVING (COUNT (CUSTOMER_ID) > 1)
ORDER BY COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME
This query only gets me half way there, as I can only visually inspect
what's returned. Here's a sample of the returned data:
Company_ID Customer_ID Customer_Name Num_Occur
R12 1 Jim Jones 2
R9 1000 Chris B 3
R9 1000 Brian P 5
R9 1001 Dave B 8
In this example, I ONLY want to return records 2 & 3 where the Company_ID,
and Customer_ID are the same, but the Customer_Names differ.On Thu, 19 Jan 2006 08:07:03 -0800, Eric wrote:

>I have a Transactions table w/the following columns (all VarChar):
>CustomerID,
>Customer_Name,
>User_Name
>And and Admin table w/the following columns (VarChar):
>User_Name,
>Company_ID
>Now I want to return any records where the CustomerID is duplicated for
>different Customer_Names when Grouped by Company_ID. Here's a sample of wh
at
>the returned data will look like:
>Company_ID Customer_ID Customer_Name
>R9 321 Ted Smith
>R9 321 Rob Wand
>Here's my query:
>SELECT COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME,
> COUNT (CUSTOMER_ID) AS NUM_OCCUR
>FROM TRANSACTIONS
>INNER JOIN ADMIN ON
> ADMIN.USER_NAME = TRANSACTIONS.USER_NAME
>GROUP BY COMPANY_ID, CUSTOMER_NAME, CUSTOMER_ID
>HAVING (COUNT (CUSTOMER_ID) > 1)
>ORDER BY COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME
>This query only gets me half way there, as I can only visually inspect
>what's returned. Here's a sample of the returned data:
>Company_ID Customer_ID Customer_Name Num_Occur
>R12 1 Jim Jones 2
>R9 1000 Chris B 3
>R9 1000 Brian P 5
>R9 1001 Dave B 8
>In this example, I ONLY want to return records 2 & 3 where the Company_ID,
>and Customer_ID are the same, but the Customer_Names differ.
Hi Eric,
Try if this works for you:
SELECT a.Company_ID, t.CustomerID, t.Customer_Name
FROM Admin AS a
INNER JOIN Transactions AS t
ON t.User_Name = a.User_Name
WHERE EXISTS
(SELECT *
FROM Transactions AS t2
WHERE t2.CustomerID = t.CustomerID
AND t2.User_Name <> t.User_Name)
(untested - see www.aspfaq.com/5006 if you prefer a tested reply)
Hugo Kornelis, SQL Server MVP