Incrementing Within A Group/Subset

Oct 6, 2006

I could do this even with my limited knowledge of SQL but I'm sure
there's a slick way that might be dead easy. My way hardly seems worth
the effort . If not thanks anyway



Col1Col2Col3
QW
QW
QW
QA
QB
QB
QXW
QXW
QXW
QXA
QXB
QXB


Every time there is a change of group (Col1 and Col2), I want to start
and increment Col3 so I end up with;
Col1Col2Col3
QW001
QW002
QW003
QA001
QB001
QB002
QXW001
QXW002
QXW003
QXA001
QXB001
QXB002

View 1 Replies


ADVERTISEMENT

Incrementing And Concatentating Non-Auto Incrementing Fields

Mar 11, 2008

My SQL table has the
following columns:













ID – Auto IncrementingNumber_of_Records – IntAccount_Number – Varchar
(Format 1234)Account_Number_Instance  – Varchar 
(Format e.g. 1234-01)Other_Field1Other_Field2…etc.



When the Account_Number was
initially inserted into the table, a Stored procedure (not written be me)  was used to concatenate the Account_Number
and Number_of_Records.  As a result
the  Account_Number_Instance became,
e.g. 1234-01, etc.



From the ASPX form we
retrieve each of the fields above, and based on the Number_of_Records an
appropriate number of records were inserted for the Account_Number. 

 

For Example:

 



Account_Number = 12345Number_of_Records = 4



The result inserted into the
table were as follows:



ID        # of Records            Acct_Number  
New_Num            Acct_Number_Instance   â€¦

1          4                                              12345                                     12345-01

2          4                                              12345                                     12345-02

3          4                                              12345                                     12345-03

4          4                                              12345                                     12345-04

 

Now, I would like to UPDATE
this table, and based on the original Number_of_ Records (4) I want to ADD, for
Account_Number (1234) add an appropriate Number_of_Instances, beginning with
the next incremental number and adding what the New Number of Records input is…




For Example:





            Account_Number = 12345            New_Num(ber_Of Records) = 3

ID        # of Records              Acct_Number    New_Num             Acct_Number_Instance   …

1          4                                              12345                                     12345-01

2          4                                              12345                                     12345-02

3          4                                              12345                                     12345-03

4          4                                              12345                                     12345-04

5                                                         12345             3                      12345-05

6                                                         12345             3                      12345-06

7                                                         12345             3                      12345-07

 

I
do realize that the next time I have to update this Account_Number I am also
going to have to somehow ADD only one of the #_of_Records and New_Num for the
Acct_Number instances to obtain the next starting number, which in the example
above would be (8)…



Any
and all suggestions on how to accomplish this would be greatly appreciated!

Thanks

View 2 Replies View Related

How Would I Get A Subset Of This?

Apr 30, 2008

I have an employee table (empl), and a labor table (lab). The labor table is populated whenever an employee clocks in/out. If an employee does not clock in, they do not appear in the labor table.

I need to capture employees whose time is less than 8 hours, or whoever did not log in at all that date. If I run the following query without a WHERE clause, I get all of my employees, with NULL data in the labor table if they did not log in that day. This is good.

However, if I add

WHERE (DATEDIFF(s, tt.StartTime, tt.EndTime) < 28800) OR (tt.StartTime = NULL)

I get all employees whose time is less than 8 hours, but do not get any of the employees who did not work at all that date, and that's expected... there should NEVER be a NULL in the labor table - it is populated whenever somebody clocks in/out.

So, how would I query the resulting table to get those that worked less than 8 hours, and those that did not?


select
et.EmpNo
et.FirstName,
et.LastName,
tt.StartTime,
tt.EndTime,
DATEDIFF(s, tt.StartTime, tt.EndTime) as Seconds

FROM (select
empl.EmpNum as EmpNo,
empl.FFName as FirstName,
empl.FLName as LastName
from
empl where empl.ftermdate IN ('1900-01-01 00:00:00.000') AS et

LEFT JOIN (select
MIN(lab.StartDt) as StartTime,
MAX(lab.EndDt) as EndTime,
lab.WorkDt as WorkDate,
lab.EmpNum as EmpNo
from
lab where lab.WorkDt in ('2008-03-03 00:00:00.000')
group by lab.WorkDT, lab.EmpNum) AS TT

ON et.EmpNo = tt.EmpNo

View 2 Replies View Related

Max Col In A Table Subset

May 1, 2007

hi i have a table as follows:

col1 col2 col3
2 BB 2
1 AB 3
3 CA 3
1 AC 1
2 BA 4
3 CB 2
2 BC 6
1 AA 2
3 CC 5

i want to output the whole row of each unique col1 where its col3 is max, so that i will get the ff result set
1 AB 3
2 BC 6
3 CC 5

i have an idea which is to use a cursor but i don't know the best/fastest way of doing it.
thanks heaps in advance!

View 1 Replies View Related

Subset A Dataset

Jul 11, 2007

I am trying to exclude patients from a dataset. There are multiple records per patid in this dataset. I have the following code:

SELECT meds.PATID, meds.MEDICATION, meds.MEDTYPE
FROM meds INNER JOIN patient ON meds.PATID = patient.PATID
WHERE (((meds.MEDTYPE) Not In ("FI (Fusion Inhibitor)","NNUC (","Non-nucleoside","NRTI & NNUC","NRTI (Nucleoside/tide Rev","PI (Protease Inhibitor)")));

I want to exclude all patient records if the patient had any of the above exclusions ever. If they have the exclusion if one record get rid of the rest of the records for that patient. Right now the code only excludes the particular record.

View 6 Replies View Related

Use DISTINCT On Subset Of All Fields

Jul 5, 2001

My table contains customer records with multiple records per customer. As a result of a query, I´m only interested in one record per customer with the highest value of a certain field in the record.

I thought of using DISTINCT, but can I use DISTINCT on a subset of all fields? Or sort the table in a certain way that the query result only shows the first unique records for a customer.

Other ideas are welcome to.

View 4 Replies View Related

Updates All Records Instead Of A Subset?

Dec 28, 2012

I am trying to update a small subset of records of a given table (TRValue) using the records contained in ParcelTemp. The difficult part is getting the summation from a child file, TRGreen, for those same parcels contained in ParcelTemp. Instead of updating just a few records, all the records in TRValue are being updated, with the wrong values of course!

Basically, Update records in TRValue that are equal to:

Year = P.Year
Code = 'LG01'
Parcel = P.Parcel

with the summation of child records where the child records needed are:

Year = P.Year
Parcel = P.Parcel

Code:
UPDATE TRValue SET
Acres = SumAcres,
CurrentMarket = SumMarket,
CurrentTaxable = SumTaxable,
CurrentTaxAmt = ((SumTaxable * D.CertifiedRate) + 0.50)
FROM ParcelTemp P

[code]....

View 4 Replies View Related

Picking A Representative Subset?

Feb 5, 2013

The problem is to find a subset of rows such that each value in each of two columns (animals and food brands in this example) appears in at least one row. The purpose is to produce a set of samples from a large table. The table has a animal_name column and an food_brand column; I want a set of samples that contains at least one of each animal_name and at least one of each food_brand, but no more than necessary.

CREATE TABLE Feeding_Options
(license_nbr INTEGER NOT NULL PRIMARY KEY,
animal_name VARCHAR (10) NOT NULL,
food_brand VARCHAR(15) NOT NULL);
INSERT INTO Feeding_Options
VALUES
(6401715, 'rat', 'IAMS'),

[code]....

To frame the problem better, her are the values in each column:

animals = {'rat', 'dog', 'cat', 'fish', 'fox'}
food = {'IAMS', 'Sci Diet', 'Purina', 'Alpo'}

In this data, (6401715, 'rat', 'IAMS') and (1058337, 'rat', 'IAMS') are interchangeable, as are some of the other rows. There can be more than one minimal solution whcihmight be the whole set.

View 2 Replies View Related

Select A Subset Of Data

Feb 13, 2007

How would I write a select statement that would return multiple fields in a records based on a a distinct of one of those fiels.

Example

Table Name : Sales Table
Field Name : Name Address Phone Zip Sale
Rec1: Peter Smith 12 Market St 999-999-9999 12345 99.99
Rec2: John Jones 73 Broadway 999-999-8888 12345 12.34
Rec3: Charle Brown 42 Peanuts Ave 999-999-7777 12345 34.56
Rec4: Peter Smith 12 Market St 999-999-6666 12345 67.89
Rec5: John Jone 73 Broadway 999-999-5555 12345 36.52

How would I be able to return the columns Name Address and Phone based on the distinct of Name.

View 4 Replies View Related

Same Table - Subset Of Info

Oct 25, 2007

I'm beating my head up against a wall here. I have one very LARGE table called op_hist.

CREATE TABLE [dbo].[op_hist] (
[op_trnbr] [int] NOT NULL ,
[op_type] [varchar] (80) ,
[op_date] [smalldatetime] NULL ,
[op_act_setup] [decimal](38, 10) NULL ,
[op_act_run] [decimal](38, 10) NULL ,
[op_qty_comp] [decimal](38, 10) NULL ,
[op_wkctr] [varchar] (80) ,
[op_part] [varchar] (30)

)

I need to be able to sum items grouped by op_wkctr and op_part and op_date. Here's my latest version which of course does not work.

SELECT op_wkctr, pcs, hrs.b
FROM
dbo.op_hist
INNER JOIN
(
SELECT op_part, SUM(op_qty_comp) as pcs
FROM dbo.op_hist
where op_type='BACKFLSH'
group by op_hist.op_part

UNION ALL

SELECT op_part, SUM(op_act_setup + op_act_run) as b
FROM dbo.op_hist
where op_type='LABOR'
group by op_hist.op_part
) AS hrs
ON op_hist.op_part = hrs.op_part
where (op_wkctr = 'P-P36' or op_wkctr = 'P-P38' or op_wkctr='P39') and op_date ='10/22/07'

Help me oby one - you're my only hope.

Sincerely,
Frustrated!

View 4 Replies View Related

SQL Server On A Subset Of Processors

Jul 10, 2006

Can I install SQL Server on a machine and use less than the # of processor on the machine. In a UNIX world, I'd call it LPARing with Oracle and AIX, and they only let me do this with Enterprise Edition. With Windows, I think the only way is using virtual machines and attaching processors to them? Do any vendors offering LPARing? Can I take any edition of SQL Server and subcapacity price so that I only pay for the processors I'm using?



What about SS Express? It only scheds to a single core - so could I put that on a larger machine?



Thanks!

View 5 Replies View Related

Reporting Services :: Display Group Name Value Of Each Group In Column Header Outside The Group?

Sep 29, 2015

I have an SSRS 2012 table report with groups; each group is broken ie. one group for one page, and there are multiple groups in multiple pages.

'GroupName' column has multiple values - X,Y,Z,......

I need to group 'GroupName' with X,Y,Z,..... ie value X in page 1,value Y in page 2, value Z in page 3...

Now, I need to display another column (ABC) in this table report (outside the group column 'GroupName'); this outside column itself is another column header (not a group header) in the table (report) and it derives its name partly from the 'GroupName'  values:

Example:

Value X for GroupName in page 1 will mean, in page 1, column Name of ABC column must be ABC-X Value Y for GroupName in page 2 will mean, in page 2, column Name of ABC column must be ABC-Y Value Z for GroupName in page 3 will mean, in page 3, column Name of
ABC column must be ABC-Z

ie the column name of ABC (Clm ABC)  must be dynamic as per the GroupName values (X,Y,Z....)

Page1:

GroupName                 Clm ABC-X

X

Page2:

GroupName                 Clm ABC-Y

Y

Page3:

GroupName                 Clm ABC-Z

Z

I have been able to use First(ReportItems!GroupName.Value) in the Page Header to get GroupNames displayed in each page; I get X in page 1, Y in page 2, Z in page 3.....

However, when I use ReportItems (that refers to a group name) in the Report Body outside the group,

I get the following error:

Report item expressions can only refer to other report items within the same grouping scope or a containing grouping scope

I need to get the X, Y, Z ... in each page for the column ABC.

I have been able to use this - First(Fields!GroupName.Value); however, I get ABC-X, ABC-X, ABC-X in each of the pages for the ABC column, instead of ABC-X in page 1, ABC-Y in page 2, ABC-Z in page 3, ...

View 4 Replies View Related

Returning A Subset Of Rows From A Query

Apr 19, 2001

This question has been posted on the site before but I could not find any resolution....I want to return rows 11 - 20 from a query that returns 100 records without using a cursor or temp table.

The closest query I have found is a query that numbers the rows, but I can't seem to use rownumber in a between clause...

Use Pubs
SELECT emp_id, lname, fname, job_id,
(SELECT COUNT(*) FROM employee e2 WHERE e2.emp_id <= e.emp_id AND e2.job_id = 10) AS rownumber
FROM employee e
WHERE job_id = 10
ORDER BY emp_id

Thanks,

Jim

View 1 Replies View Related

Calculate Check Digit On Subset Of Ids

Jul 17, 2006

how do i calculate all the checkdigits for a subset of ids and return all the ids and checkdigits? basic calculation isn't the problem, just how to select the ids and utilize the ids in the calc. I am new to trying to do calculations on data.

View 7 Replies View Related

Selecting The First Instance Of Each Record From A Subset

May 21, 2001

Hi

I'm sure this is an easy problem but my brain is fried today...however how do I do the following:


I have a two column table. One is a key field where duplicates can arise and the other is a datetime field. So you might have some records looking like this:

1231999-06-14 12:17:11.000
1231999-06-14 12:17:31.310
1231999-06-14 12:17:31.000
1231999-06-14 12:22:56.000
1231999-06-14 12:22:58.000
8901999-06-15 10:00:18.000
8901999-06-15 10:03:30.340
8901999-06-15 10:03:30.000
8901999-06-15 10:03:40.000

OK, how do I get the top 1 of each key so that I get a subset of records looking like the following:
1231999-06-14 12:17:11.000
8901999-06-15 10:00:18.000


Thanks in advance


Bazza

View 1 Replies View Related

Transfer Of Subset Of Data To/from Notebook

Mar 25, 2004

I have a need to dump a subset of a database from the server (SQL Server) to a notebook via the network, for data entry to be done on the notebook when it is in the field & not connected to the network & then the changes made to this data on the notebook to be applied to the database on the server.

The application for the front end to this is in Access. Would MSDE be the way to go for the database on the notebook ?

It's a small application with not many users, likelihood of conflicting edits is small.

Would the data transfer best be done with replication or with DTS ?
Presumably replication would allow options for control over conflicts, such as the same bit of data being changed on the server & on the notebook’s copy of the data ?

I need guidance re direction to head in with this.

Thanks

View 2 Replies View Related

Count Of Contacts - Data Subset?

Jan 29, 2014

I am trying to get counts of contacts.

So how do I subset, to gain a the accounts with the products then query to gain the contact counts from those accounts?

But for some reason it's giving me counts of products.

select distinct
a.region__c as [Region],
a.SFTX_ID as [SFTRX ID],
count(c.Contact_ID) as [Contact Count]
from vwContact c

[Code] .....

View 1 Replies View Related

Nth Subset Of Data From Current Table

Jul 20, 2005

Hi,I was wondering if you guys have any nth script to reads from tableand outputs into a temp table subset of records. There was a nth toolI used to use it was GROUP1 which was written in C and it used to bevery fast on nth -in a flat file. In this program we used to pass fewparamaeters. For example if I want 30,000 records from the file of500,000. The function seams to work something like this. you dividethe 30,000 records of 500,000 which will result with .090909090909.Now we would pass only the first 7 digit (0909090) as parameter thatwould nth the file down to 30,000 records. This function allwaysworked whichever number you use as long as the read file is largerthan output fileI like to use the similar concept in Sql Server and I was wondering ifanyone has any script to do this or how to go about this?Thank you. I appreciate your feedbackagron

View 1 Replies View Related

Selecting A Subset Of The Search Results

Nov 2, 2007

I want to break up a set of search results into small chunks. For instance, think about how Google displays a block of ten results out of the entire set. Selecting the top 10 is dead easy with "TOP 10"; how do I select the next 10?


Obviously one option would be to select the top 20, and programmatically discard the first 10, but surely there is a better way? I am doing this for a ASP.NET 2.0 application, and if I can retrieve just what I want, I can DataBind to a Repeater, and let ASP.NET do all the hard work of displaying the data.

View 4 Replies View Related

Analysis :: Subset Function In MDX Query

May 18, 2015

I need other function act like subset function using mdxquery.

In my mdxqueries,contain subset,order functions are available.

subset and order is getting poor query performance.

View 8 Replies View Related

Return Subset With All Remaining Records

Feb 22, 2008

Hello,

I need to pull records from single table such that I get a subset defined like this:

(
acctcode = 'xh364'
and
product = 'T&E'
)

And return all of the rest of the records:

(
acctcode = '%'
and
product = '%'
)

Can I do this within a WHERE clause, or will this require CASE / ELSE? There will be other specific acctcode/product rules that will be added later. I could do this with a UNION, but I need to avoid that if possible.


Thank you for your help!


cdun2

View 6 Replies View Related

Incrementing

Nov 21, 2007

Hi,

I currently have a table which has around 60000 records, within the table there is a field which is acting as the Primary but the numbers are not in consecutive order any more (due to deletion), and i need a SQL Script that will start at the beginning of the records and UPDATE (STK_LOCATION) and SET the field (LOC_PRIMARY) to 1 on the first record and then go through the rest of the table setting the same field to +1 of the record before it.

Any help and advice will be very grateful

Thanks in advance

View 3 Replies View Related

Incrementing A Value

Apr 27, 2007

I have just started using SSIS this week. I am experienced with a different ETL tool (DataStage).



What I am trying to accomplish is the following:

Read the MaxValue of a Key from a Table and match to a stream of data using a LookUp stage.
Increment the value of each row for insertion to the table where I obtained the MaxValue.

What would seem to be a very simple procedure (I could knock this out in 10 minutes with DS...of course I have more experience with that toolset) is problematic for me. I would just use a Transform stage and add the RowNumber variable to the MaxValue for each row. The stream would be ready for Insertion to the target table.



I am currently trying to use a Script Component in the Data Flow. Since my VB is rusty, does anyone have a script for incrementing a ReadWrite Variable for insertion to the stream? All I want to do is take the MaxValue and add the RowNumber or increment by 1 each time the script is performed.



If anyone has a simpler method, please let me know. Also, before it starts, yes we are using the Identity feature on the table, however due to processing constraints we need to preassign the Key in our Data Flow. Hence the incrementing of rows....



Cheers.

View 3 Replies View Related

Most Efficient Way To Count Subset Of Rows In A Table?

Sep 14, 2005

Hi all,
I’ve a table with production objects, and another with possible items composition of the object. I need to count how many occurrences of each standard composition appears:
Table PROD:
PROD_ID    COMPONENT   TYPE
--------- ----------- -----
1         AAA         X1         BBB         Y2         AAA         X3         BBB         Y4         AAA         Y5         AAA         X5         BBB         YTable ITEM_COMPITEM_ID   COMPONENT   TYPE--------  ---------   -----7         AAA         X7         BBB         Y8         AAA         X9         BBB         Y
The result should be:
ITEM_ID   OCCURRENCES--------  ----7         28         19         1
Table PROD have millions of rows, my way is too slow (I’ve a loop where each PROD object are separately queried against the ITEM_COMP), some have an idea for a most efficient way?
 
ThX
 
NeuralC
 
 

View 2 Replies View Related

Can I Select Subset Based On Time Of Entry

Jul 5, 2001

A table gets data every 4 minutes, I only need spread of every 15 minutes. Can I select only records spread every 15 minutes apart from this table without having to run a scheduled job every 15 minutes and loading one record closest to getdate() at that point into another table(this is how I am doing it now) Is there a better way. Please help
Thanks

View 2 Replies View Related

Move A Subset Of Data From Production To Test

Nov 18, 2005

Here is my requirement.

There is a production database which has ever increasing data. For testing purposes though, I would like to build a test database with exactly the same schema but only a subset of data copied from the production database . I'll specify the criteria (something like a where clause in select query) for copying the data from the production database.

Is there a tool that anyone has come across to do this job ?

View 2 Replies View Related

Should I Have A Table That Stores A Subset Of Data From Other Tables???

Mar 21, 2007

DB design question

I have multiple tables with information about a user. The tables are Roles, Users, Groups and Profiles.

For a user session I need information from all those tables. Would it be better to make a table called UserSession and collect the necessary data from the above mentioned tables and stick them in one the UserSession table or should I just write a query that goes out and gets the data from the different tables.

What is better practice and what is faster?

View 4 Replies View Related

Analysis :: Subset Dimension Linked Two Times?

Aug 6, 2015

I have a cube with some dimensions (dim1,dim2,dim3).I want to add another dimension (dim4) based on dim1 but more restricted.Eg. Dim1 is a product dimension, and I will create Dim4 from a subset of Dim1 (only few and predetermined products).

I will create a view (or a named query) with the appropriate where clause, create a dimension on this view/namedQ, then add on the existant cube and link it on dimension usage. Great. But in this way in the cube I haven't all fact data but only data for the product of Dim4! (Dim1 is still present).

eg: in fact data I have a total of 100$ of sales for all the products, if I link the Dim4 then the sales amount is 40$, that is the value for the product in Dim4 not for all product (I can't set the filter for Dim1/Dim4 in excel). I haven't found any way for get the 100$.

I try with two Date dimension: the first from 01/01/2010 to 31/12/2015 and the second from 01/01/2015 to 31/12/2015. If I link both I see only data for the second period (only 2015).

it seems that the more restrictive dimension trumps.What's wrong? There are other ways to get what I want? I've tried the property "DependOnDimension" but without results.

I won't publish the attribute used in the WHERE clause on the dimension.

BIDS 2008 and SQL Server 2008R2

View 2 Replies View Related

Help: Should Sys.service_queues.object_id Be Subset Of Sys.dm_broker_queue_monitors.queue_id?

Apr 4, 2007



I am having trouble sending messages between service broker, set up on 2 different machine ( different domain ). The ports on which service brokers listening are bidirectional.



for some reason the messages get piled up at the sys.transmission_queue and transmission_status seems to be empty.



I found the following link and tried to find status of all message queues.

http://msdn2.microsoft.com/en-us/library/ms177628.aspx

SELECT t1.name AS [Service_Name], t3.name AS [Schema_Name], t2.name AS [Queue_Name],
CASE WHEN t4.state IS NULL THEN 'Not available'
ELSE t4.state
END AS [Queue_State],
CASE WHEN t4.tasks_waiting IS NULL THEN '--'
ELSE CONVERT(VARCHAR, t4.tasks_waiting)
END AS tasks_waiting,
CASE WHEN t4.last_activated_time IS NULL THEN '--'
ELSE CONVERT(varchar, t4.last_activated_time)
END AS last_activated_time ,
CASE WHEN t4.last_empty_rowset_time IS NULL THEN '--'
ELSE CONVERT(varchar,t4.last_empty_rowset_time)
END AS last_empty_rowset_time,
(
SELECT COUNT(*)
FROM sys.transmission_queue t6
WHERE (t6.from_service_name = t1.name) ) AS [Tran_Message_Count]
FROM sys.services t1 INNER JOIN sys.service_queues t2
ON ( t1.service_queue_id = t2.object_id )
INNER JOIN sys.schemas t3 ON ( t2.schema_id = t3.schema_id )
LEFT OUTER JOIN sys.dm_broker_queue_monitors t4
ON ( t2.object_id = t4.queue_id AND t4.database_id = DB_ID() )
INNER JOIN sys.databases t5 ON ( t5.database_id = DB_ID() )



What I noticed is the values of sys.service_queues.object_id and sys.dm_broker_queue_monitors.queue_id are totally different. I am not sure whether this has any impact on why the messages are stuck at transmission_queue



object_id

-----------

21575115

1977058079

2009058193

2041058307

2073058421

2105058535

2137058649

(7 row(s) affected)

queue_id

-----------

864722133

896722247

(2 row(s) affected)

View 4 Replies View Related

Only Small Subset Of Rows Replicates To MySQL

May 1, 2007

I have been messing around with trying to replicate sql server 2000 tables to postgres as well as mySQL. I'm starting with just one table and trying to get that working, it has around 9000 rows, all of which copy to postgres (with some datatype issues).

However, when I try to replicate to a mySQL database however, only the same 152 rows get copied every time.

I compared rows that were copied to ones that were not to see if there was any obvious differences between the two and couldn't find any.

View 1 Replies View Related

Custom Paging - Getting A Subset From 2 Tables By UserID

Apr 7, 2008

I am trying to implement custom paging. I want to get a subset from my Threads and Post tables by userID. But I can't make the stored proc work. Could somebody have a look at this and tell me what I am doing wrong or if there is a better way of doing this?

ALTER PROCEDURE [dbo].[syl_ThreadPost_GetSubsetSortedByUserID2]

@UserID uniqueidentifier,

@sortExpression nvarchar(64),

@startRowIndex int,

@maximumRows int

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON

BEGIN TRY

IF LEN(@sortExpression) = 0

SET @sortExpression = 'PostID'

-- Since @startRowIndex is zero-based in the data Web control, but one-based w/ROW_NUMBER(), increment

SET @startRowIndex = @startRowIndex + 1

-- Issue query

DECLARE @sql nvarchar(4000)

SET @sql = 'SELECT t.[ThreadName],

p.PostID,

p.[PostTypeID],

p.[LanguageID],

p.[PostAccessID],

p.[UserID],

p.[ThreadID],

p.[PostParentID],

p.[VoteSummaryID],

p.[Subject],

p.[Body],

p.[PostAuthor],

p.[PostDate],

p.[IsApproved],

p.[TotalViews],

p.[FormattedBody],

p.[IPAddress],

p.[PostCount],

p.[ArticleCount],

p.[TrackbackCount],

p.[IsSticky],

p.[StickyDate]

FROM

(SELECT t.[ThreadName],

p.PostID,

p.[PostTypeID],

p.[LanguageID],

p.[PostAccessID],

p.[UserID],

p.[ThreadID],

p.[PostParentID],

p.[VoteSummaryID],

p.[Subject],

p.[Body],

p.[PostAuthor],

p.[PostDate],

p.[IsApproved],

p.[TotalViews],

p.[FormattedBody],

p.[IPAddress],

p.[PostCount],

p.[ArticleCount],

p.[TrackbackCount],

p.[IsSticky],

p.[StickyDate],

ROW_NUMBER() OVER(ORDER BY ' + @sortExpression + ') AS RowNum

FROM syl_Threads t RIGHT OUTER JOIN syl_Posts p

ON t.[ThreadID] = p.[ThreadID])

WHERE t.[UserID] = ' + CONVERT(nvarchar(16), @UserID) + ' )

AS syl_ThreadPostInfo

WHERE RowNum BETWEEN ' + CONVERT(nvarchar(16), @startRowIndex) + ' AND (' + CONVERT(nvarchar(16), @startRowIndex) + ' + ' + CONVERT(nvarchar(16), @maximumRows) + ') - 1'

-- Execute the SQL query

EXEC sp_executesql @sql

RETURN

END TRY

BEGIN CATCH

--Execute LogError_Insert SP

EXECUTE [dbo].[syl_LogError_Insert];

--Being in a Catch Block indicates failure.

--Force RETURN to -1 for consistency (other return values are generated, such as -6).

RETURN -1

END CATCH

END

View 4 Replies View Related

Incrementing Id Field

Mar 21, 2004

Hi

Does anyone know why an error occurs (constraints violated) when I try to have a table with an automated id incrementing by 1. I am uploading the data into the table from dts, so ignore the id field in the dts transformation.

Any ideas or help would really be appreciated, do I need to reference the id field in an activeX script?

Thanks

View 9 Replies View Related

Incrementing Primary Key

May 13, 2004

hi am new in this forum and am designind a database in SQLserver and i want to make the primary key auto incremented
can anyone help

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved