How To Increment Field After Selecting It

Oct 26, 2007

I have  FeaturedClassifiedsCount  field, which I would like to update each time record is selected. How do I do it in stored procedure on SQL 2005?

This is my existing code:alter PROCEDURE dbo.SP_FeaturedClassifieds

@PageIndex INT,

@NumRows INT,

@FeaturedClassifiedsCount INT OUTPUT

 

AS

BEGIN

select @FeaturedClassifiedsCount = (Select Count(*) From classifieds_Ads Where AdStatus=100 And Adlevel=50 )

Declare @startRowIndex INT;

Set @startRowIndex = (@PageIndex * @NumRows) + 1;

 

With FeaturedClassifieds as (Select ROW_NUMBER() OVER (Order By FeaturedDisplayedCount * (1-(Weight-1)/100) ASC) as

Row, Id, PreviewImageId, Title, DateCreated, FeaturedDisplayedCountFrom

classifieds_Ads

WhereAdStatus=100 And AdLevel=50

)

 

SelectId, PreviewImageId, Title, DateCreated, FeaturedDisplayedCount

From

FeaturedClassifieds

Where

Row between@startRowIndex And @startRowIndex+@NumRows-1

 

END

View 1 Replies


ADVERTISEMENT

SQL Server 2008 :: Selecting Field That Contains Data From Another Field

May 28, 2015

We have a stock code table with a description field and a brand field - when the data was entered, some of the records were entered with the brand field in the description field.

ie.
Code Description Brand
ABC1 BLANK DVD SONY
ABC2 SONY BLANK DVD SONY

what I need to do is identify where the Brand is in the Description field ...

I have tried ;

select * from Table
where Description Like Brand

not very successful.

View 3 Replies View Related

Selecting Field And Sum Of Field Issues Error.

Feb 19, 2007

With this query:
SELECT Table1.1ID, Table1.Field1, Table2.2ID, Table2.Field1, Table3.3ID, Table3.Field1, sum(Table1.Field1), sum(Table2.Field1), sum(Table3.Field1)
FROM Table1 INNER JOIN
Table2 ON Table1.1ID = Table2.2ID INNER JOIN
Table3 ON Table2.2ID = Table3.3ID

I get this error:
Column 'fieldname' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.

Is it because you can't do what I'm trying above or am I missing something?

Thank you!

--PhB

View 1 Replies View Related

A Good Way To Increment Field Value

Nov 15, 2007

 HiI have a field containing numbers. I want to do some simple arithmetics with it, say value=value+1 or value=value-1 or or even value+2. What is to be done, is fixed at design time. I think this could be done by loading the row or record to my program and doing the calculations there. And then storing the record back. But this seems too complicated.Is there a single query doing that in data table. 

View 3 Replies View Related

[*-)] About Auto Increment Field

Nov 27, 2007

Hi,
I have one Auto increment field in the table.
I have a problem that suppose I have 10 Records in the table, Now If someone delete record no 3 and 5 then it has 8 records.
But The field will give 11 no to new record I want it first fill 3 and 5 then give 11 to the new record.
Is it possible with the auto increment field in sql server 2005.
 

View 1 Replies View Related

Auto Increment Field

Apr 5, 2008

Hey,
Im building a site within Visual Studio 2005 and im using the SQL database system it provides. I currently have a number of tables each with a primary key that is set to the 'int' field type and also set to auto increment 1, 2, 3 etc etc. My question is it there a way to make this field increment automatically, providing a unique value but also automatically placing a couple of pre-defined letters before the number? Obviously it can't be an 'int' anymore because it'll be holding something like MEM1, MEM2 etc. Is there a way to do this is Visual Studio?
 Many Thanks!

View 3 Replies View Related

How To Auto Increment A Primary ID Field?

Oct 8, 2006

I was just wondering on a very simple database table with lets say a primary key set to columb ID and another columb lets say products, can you make the primary key automaticly increment its self whenever a new entry has been put in?For instance say I have this table set up with ID Being the primary KEY, Columb 1 = ID( INT ), Columb 2 = Products ( VarChar(50) ), and have the fields ID = 1, and products = my product.....and if a user inserts a new record say from a gridview or some sort of data entry the second ID Feild will automaticly be  2 and the products gets updated per user input.......I'm very sorry but I'm having a hard time putting this into words for some reason..umm basicly user adds something into the products feild and the ID field automaticly increments one number higher from the last one?ThanksAdam.

View 4 Replies View Related

Manually Increment Values Of ID Field

Nov 4, 2014

declare @kk int
set @kk=0
insert into tblSSAppsOrgEntityToEmployerMapDiffer
(Id,
OrgEntityCode,
EmployerId,
[Default],

[Code] ...

In above example Id is PK for Differ tbl and Temp tbl not having field related to this. thats why i have to take and increment that Id value manually.... but like above way i m getting error ..........

View 5 Replies View Related

Increment An ID Field In Sql Query String

Mar 3, 2006

Hello..

can anyone help me with this query string?

String SQL = "INSERT Employee(Employee ID, UserName, JobRole, Department, Level, Email)(SELECT max(EmployeeID) + 1 FROM Employee) AS Employee ID, VALUES(EmployeeID, '" + newUserName + "', '" + newJobRole + "', '" + newDept + "', '" + newLevel + "', '" + newEmail + "')";

I am trying to insert values into a table, but i have an Employee ID field, which needs incrementing. How can i do this through my SQL query string? Is this possible? As it can't accept a NULL value.

Thanks, Sandy

View 4 Replies View Related

Auto Increment RecordID Field Value

Apr 25, 2008

Hi All,

I am trying to write a query that takes the max recordID on table A, and increment it by 1 for every record that is inserted into table A. The recordID field does not identity field property turned on.

Can you give me some help in getting this done? Is what I am trying to do even possible?

Thanks in Advance for your help.

View 9 Replies View Related

There Must Be An Easier Way - Dupe Check And Increment Field

Nov 11, 2006

Greetings all,

I have a bit of brainteaser that's going to take some serious thought.

I'm importing information from .xls files into a SQL table. The problem is I need to check for dupes and increment certain fields on success of dupe find and then not insert or delete the dupes.

For example, if I have Adam, Turner, 32, 50 already in the table and someone tries to insert Adam, Turner, 32, 50...I need it to increment to read Adam, Turner, 64, 100 and not insert the record. (Notice 2 fields were incremented.)

With that, I have created an INSERT trigger as follows:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Trigger [dbo].[trgInsertCheck]
ON [dbo].[MyTable]
FOR INSERT
AS
BEGIN
   EXEC sp_UpdateDupes
   EXEC sp_DeleteDupes
END

The first stored procedure checks for dupes and updates if any dupes are found as follows:
--------------------------------------------------------------------------------------------------------------------------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[sp_UpdateDupes] AS

DECLARE @FirstName varchar(20), @LastName varchar(20), @Age int,  @Widgets int
DECLARE c1 CURSOR FOR

SELECT FirstName, LastName, Age, Widgets
FROM MyTable
GROUP BY FirstName, LastName, Age, Widgets
HAVING COUNT(*) > 1

OPEN c1
FETCH NEXT FROM c1
INTO @FirstName, @LastName, @Age, @Widgets
WHILE @@FETCH_STATUS = 0
BEGIN



UPDATE MyTable set Widgets = Widgets + @Widgets, Age = Age + @Age
WHERE FirstName = @FirstName AND LastName = @LastName

FETCH NEXT FROM c1
INTO @FirstName, @LastName, @Age, @Widgets
END
CLOSE c1
DEALLOCATE c1

Lastly, it finds all dupes, deletes them and inserts one row back in as follows:
--------------------------------------------------------------------------------------------------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[sp_DeleteDupes] AS

DECLARE @FirstName varchar(20), @LastName varchar(20), @Age int, @Widgets int --declare all fields in table

DECLARE c1 CURSOR FOR

SELECT FirstName, LastName, Age, Widgets
FROM MyTable
GROUP BY FirstName, LastName, Age, Widgets
HAVING COUNT(*) > 1

OPEN c1
FETCH NEXT FROM c1
INTO @FirstName, @LastName, @Age, @Widgets
WHILE @@FETCH_STATUS = 0

BEGIN
--Delete all dupes...the cursor remembers the current record

DELETE FROM MyTable
WHERE FirstName IN (SELECT FirstName FROM MyTable GROUP BY FirstName HAVING COUNT(FirstName) > 1)
AND LastName IN (SELECT LastName FROM MyTable GROUP BY LastName HAVING COUNT(LastName) > 1)
AND Age IN (SELECT Age FROM MyTable GROUP BY Age HAVING COUNT(Age) > 1)
AND Widgets IN (SELECT Widgets FROM MyTable GROUP BY Widgets HAVING COUNT(Widgets) > 1)

--insert the current record back into the table

INSERT INTO MyTable(FirstName, LastName, Age, Widgets) VALUES(@FirstName, @LastName, @Age, @Widgets) 

FETCH NEXT FROM c1
INTO @FirstName, @LastName, @Age, @Widgets
END
CLOSE c1
DEALLOCATE c1

Is there an easier way to do this?

(I know Age doesn't make much sense in this example but just replace it with a field would logically be incremented such as wadgets.)

Adamus

View 7 Replies View Related

Transact SQL :: How To Update A Field And Insert Increment Count

May 28, 2015

I want to update a field and in this field insert a increment count, for example:

When I make, "Select * from Users order by User" displays:

User1  |  NULL
User1  |  NULL
User1  |  NULL
User2  |  NULL
User2  |  NULL

and I want to do this:

User1  |  1
User1  |  2
User1  |  3
User2  |  1
User2  |  2

how to do this?

View 7 Replies View Related

Selecting The Same Field Twice

Sep 6, 2005

CREATE PROCEDURE {databaseOwner}{objectQualifier} [PreciseData_IssueTracker_GetAllIssues]@moduleId intASSELECT PreciseData_IssueTracker_Issue.id AS 'issueId',PreciseData_IssueTracker_Status.name AS 'statusName',PreciseData_IssueTracker_Issue.subject AS 'subject',PreciseData_IssueTracker_Type.name AS 'typeName',Users.Username AS 'assignedUserName',Users.Username AS 'raiserUserName',PreciseData_IssueTracker_Issue.raiseDate AS 'raiseDate'FROMPreciseData_IssueTracker_Issue INNER JOIN PreciseData_IssueTracker_Status ON PreciseData_IssueTracker_Issue.statusId=PreciseData_IssueTracker_Status.idINNER JOIN PreciseData_IssueTracker_Type ON PreciseData_IssueTracker_Issue.typeId=PreciseData_IssueTracker_Type.idINNER JOIN Users ON Users.UserID=PreciseData_IssueTracker_Issue.assignedUserIdINNER JOIN Users ON Users.UserID=PreciseData_IssueTracker_Issue.raiserUserIdWHERE PreciseData_IssueTracker_Issue.moduleId=@moduleIdORDER BY PreciseData_IssueTracker_Issue.raiseDate DESCGOHow do i make it work?

View 1 Replies View Related

Selecting Another Field From The Row With The Max

Sep 7, 2006

For a select statement like:

select f1, max(f2), f3 from t group by f1

how do I say 'f3 from the same record that you found the max of f2'?

Thanks!

View 4 Replies View Related

Selecting The Two Biggest Values Of A Field

Mar 13, 2006

I need to do a SQL query based on the two biggest values of a field. PLS , what s the SQL syntax : select * from Table where PRICE ......Ex: if the values of the field PRICE are : 50, 40, 100, 30 and 150.The request should select the rows that have Price equal 100 or 120Thanks a lot for help

View 2 Replies View Related

Selecting The Two Biggest Values Of A Field

Mar 13, 2006

I need to do a SQL query based on the two biggest values of a field. PLS , what s the SQL syntax : select * from Table where PRICE ......

Ex: if the values of the field PRICE are : 50, 40, 100, 30 and 150.

The request should select the rows that have Price equal 100 or 120

Thanks a lot for help

View 5 Replies View Related

Selecting From Two Tables, And Sorting By Common Field.

Feb 10, 2002

This is feeling very hard for me, but is surely very easy for many of you.
I have 2 Tables. "Events" and "Meals". Both have a columns named "EventDate" and "EventTime". I need to be able to compile a list of both and sort by event date and time. For example, a Meal @ 5:30 would place itself between a 4:00 Event, and a 6:30 Event.

PLEASE HELP ME!!!
Pending deadline doom :(

Thanks,
kaskenasy@publishingconcepts.com

View 1 Replies View Related

Selecting A Field In Every Tuple & Making It Bold

Nov 19, 2007

Hi,

i have a table, that i am trying to compare values. I want to highlight the cheapest field's contents (price) for each tuple. The field itself could be different for each field depending on its price. the table i have is below;

Pos |AlbumTitle |Artist |Virgin | Woolworths | hmv
-----+---------------+--------------+-------+-------------+---------
1 | Confessions |Usher | 2.99 | 9.99 | 13.79
2 | Back Home | Westlife | 2.00 | 5.99 | 3.19
3 | Spirit |Leona | 5.99 | 2.99 | 13.99
4 | Trust Me |Craig David| 7.99 | 11.99 | 6.63
5 | Sawdust |Killers | 22.99 | 10.99 | 8.39
6 | Greatest Hits |Spice Girls| 12.99 | 0.99 | 13.79

im not sure if this would be a good format for the table, i cant figure out how to find out which field is the lowest value and how at all i would be able to make the value itself bold or stand out somehow.

Any help/advice would be welcome!!!
Rich

View 3 Replies View Related

Selecting A Top Record Based On A Datestamp Field

Jan 30, 2008



This is a simple one, and I know that it has to be fairly common, but I just can't figure out an elegant way to do it. I have a table with the following fields:
OrderID (FK, not unique)
InstallationDate (Datetime)
CreateDtTm (Datetime)

There is no PK or Unique ID on this table, though an combo of OrderID and CreateDtTm would ostensibly be a unique identifier.

For each OrderID, I need to pull the InstallationDate that was created most recently (based on CreateDtTm). Here's what I've got so far, and it works, but man is it ugly:



SELECT a.OrderID, InstallationDate

FROM ScheduleDateLog a

INNER JOIN

(SELECT OrderID, max(convert(varchar(10),CreateDtTm,102)+'||' +convert(varchar(10), InstallationDate,102)) as TopRecord

FROM ScheduleDateLog GROUP BY OrderID) as b

ON convert(varchar(10),CreateDtTm,102)+'||' +convert(varchar(10), InstallationDate,102)=b.TopRecord

AND a.OrderID = b.OrderID

View 8 Replies View Related

Selecting Records Where Part-field Is Unique

Aug 10, 2015

I have a very large CSV file containing name-and-address information which I am reading in a Visual Basic project using the Microsoft.JetOLEDB.4.0 provider.

The key field on which the CSV file is to be filtered is the PostCode field.  This is a UK-format PostCode "XXnn Nxx" where "XX" is one or more letters denoting a geographical area within the UK and "nn" is one or more characters (starting with at least one numeric digit) which when combined with the area code denotes a specific district within the geographical area.  My aim is to identify all the unique UK postal districts held within my address CSV file.

Because I do not know how to use SQL to filter on the partial contents of a database field I am presently reduced to extracting unique full PostCodes using "SELECT DISTINCT PostCode,City,County FROM [ADDRESSES.csv]" into a DataTable object, then sequentially reading that DataTable using the operation of a dictionary object to identify unique PostCode areas, to finally construct the DataTable I need.

Is it possible in SQL to select records where the value of a varying number of characters before a space character in a given (PostCode) field is unique?

View 12 Replies View Related

Selecting Maximum From A Varchar Field In A Data Flow

May 31, 2006

I have a problem selecting maximum values inside a data flow, when the field is varchar. For example, I could have an incoming text file with following rows (the real life problem is a bit more complicated, but the idea is the same)

ID Desc
1 Car
1 Truck
1 Bicycle
2 Horse
2 Cow

Now I would like to group by ID, and have the maximum value from the Desc field, resulting

ID Desc
1 Truck
2 Horse

I tried to sort the data flow first with ID ascending and Desc descending, followed by sort with ID ascending and "Remove duplicate sort values" turned on. However, the sort does not seem to select the first Desc value it gets, because the result is.

ID Desc
1 Bicycle
2 Horse

If you have any hints, how to tackle this problem, please help!

View 3 Replies View Related

Selecting Field From Second Table If Same Field In First Table Is Null

Nov 25, 2007



Hi,
I have one table (PermProportionalCosting) that contains employeecode, costcentre and proportionpercentage. An employee may have two or more records in this table, indicating that their salary has been split across multiple costcentres.

Another table (Employee) contains a default costcentre for each employee.

Another table (TransActualHistoricalMaster) contains the hours paid to each employee for each pay period.

My query so far selects all employees and the total hours worked from the TransMaster table, and then selects the costcentre and proportionpercentage from the PermProportionalCosting table. Multiple lines are created for all employees in the PermProportionalCosting table, with each line indicating the proportionpercentage and associated costcentre.

This is my query so far:

SELECT TransActualHistoricalMaster.EmployeeCode, Employee.PreferredName, Employee.LastName, CostCentre.Description, PermanentProportionalCosting.CostCentreCode,PermanentProportionalCosting.PercentageSplit,
TransActualHistoricalMaster.OrdHours
FROM TransActualHistoricalMaster
INNER JOIN Employee ON TransActualHistoricalMaster.EmployeeCode = Employee.EmployeeCode
INNER JOIN CostCentre ON Employee.CostCentreCode = CostCentre.CostCentreCode
FULL OUTER JOIN PermanentProportionalCosting ON TransActualHistoricalMaster.EmployeeCode = PermanentProportionalCosting.EmployeeCode
GROUP BY TransActualHistoricalMaster.EmployeeCode, Employee.PreferredName, Employee.LastName, CostCentre.Description, PermanentProportionalCosting.CostCentreCode, PermanentProportionalCosting.PercentageSplit, TransActualHistoricalMaster.OrdHours

This next bit is what I am unsure of.

I would like the CostCentre field from the Employee table to go into the PermanentProportionalCosting.CostCentreCode column where the employee doesn't have a record in the PermanentProportionalCosting table. In the above query, there is a null value for each employee that doesn't have a record in the PermanentProportionalCosting table, so I would like my query to replace the null value with the costcentre from the Employee table.

Any assistance would really be appreciated.

Thanks.

View 3 Replies View Related

Need To Have 2 Auto Increment Columns (Seed, Increment)

Dec 11, 2007

Hello,

I Have a table that needs to have 2 unique number.

detail_id and detail_print_id.

detail_id is already an IDENTITY.

both fields need to be different, because when importing, it imports the same data into a table twice, with only a slight data change (and id is not one of the changes).

So I thought i could do the following:

detail_id INT NOT NULL IDENTITY(1,2),
detail_print_id INT NOT NULL IDENTITY(2,2),
--blah blah

that way, the detail_id will always be odd, and the detail_print_id will always be even. however SQL Server 2005 only allows 1 identity per table, and both these fields need to be auto generated when the field is inserted, so as to prevent double data.

is there anyway I can create a int column to auto increment, without the column being an IDENTITY??

also, I would prefer to not have to create a second table with a single column just for this work.

Thanks,
Justin

View 5 Replies View Related

Auto Increment Auto Non-identity Field

Jan 23, 2004

I have an MS SQL Server table with a Job Number field I need this field to start at a certain number then auto increment from there. Is there a way to do this programatically or within MSDE?

Thanks, Justin.

View 3 Replies View Related

Selecting SUM From One Table As Field In Results Of Rows From Another Table.

Nov 20, 2007

Hi,
These aren't my tables, but lets dumb it down for my sake!

I have 2 tables:

CompanyInfo: IDNumber, EffectiveDate, CompanyName
TransacationInfo: TransactID, CompanyID, TransDate, Amount

There are several records in TransactionInfo for each record in CompanyInfo.

I want to:

SELECT CompanyInfo.IDNumber, CompanyInfo.EffectiveDate, CompanyInfo.CompanyName,
SUM(TransactionInfo.Amount)

How can I do this? Can I?

View 4 Replies View Related

Selecting The Most Recently Edited Item AND Selecting A Certain Type If Another Doesn't Exist

Sep 20, 2007

I've got a big problem that I'm trying to figure out:
I have an address table out-of-which I am trying to select mailing addresses for companies UNLESS a mailing address doesn't exist; then I want to select the physical addresses for that company. If I get multiple mailing or physical addresses returned I only want the most recently edited out of those.

I don't need this for an individual ID select, I need it applied to every record from the table.

My address table has some columns that look like:
[AddressID] [int]
[LocationID] [int]

[Type] [nvarchar](10)
[Address] [varchar](50)
[City] [varchar](50)
[State] [char](2)
[Zip] [varchar](5)
[AddDate] [datetime]
[EditDate] [datetime]

AddressID is a primary-key non-null column to the address table and the LocationID is a foreign key value from a seperate Companies table.
So there will be multiple addresses to one LocationID, but each address will have it's own AddressID.

How can I do this efficiently with perfomance in mind???

Thank you in advance for any and all replies...

View 2 Replies View Related

Transact SQL :: Return Field When A Field Contains Text From Another Field

Aug 25, 2015

I'm new to SQL and I'm trying to write a statement to satisfy the following:

If [Field1] contains text from [Field2] then return [Field3] as [Field4].

I had two tables where there were no matching keys. I did a cross apply and am now trying to parse out the description to build the key.

View 8 Replies View Related

How To Add Date Field And Time Field (not Datetime Field )

May 4, 2006

Good morning...

I begin with SQL, I would like to add a field that will be date like 21/01/2000.

Actually i find just "datetime" format but give me the format 21/01/2000 01:01:20.

How to do for having date and time in two different field.

Sorry for my english....

Cordially

A newbie

View 3 Replies View Related

T-SQL Increment

Oct 11, 2005

i have got 22,000 rows in a table, i want to update the records to have to start id of 70000 which increments to 70001, 70002 ? how would i go about doing this ?

View 3 Replies View Related

Increment A Value

Sep 30, 2006

Is there an easy and fast way to increment a value by 1 in a database? For example if a value is 106 I will need to make it 107. Is there a fast way to do this?

View 9 Replies View Related

Increment The Value

May 9, 2008

If there is one field such as Seq No in a table and if we entered some data ..
and if we update one record of Seq No then the below records of Seq No should be incremented in that table

for example there are 10 seq no's and if i had updated the seq no 4 to 5 then the
5 shuld b inc 6 and 6 to 7 etc............

at preasent i wrote only
update in sp of that particular record:
like this

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER PROCEDURE [dbo].[UpdateSelected]
(

@Description NVARCHAR(30),
@SequenceNo int
)
AS

UPDATE Sequence SET
Description = @Description,
SequenceNo = @SequenceNo

WHERE
SectionID = @SectionID
but now i need additional functionaly like inc the remaining sq no above that given no...

Regards,
Anushka

View 1 Replies View Related

How To Increment The Row

Jun 12, 2008

1. I have a table lets say ABC in which the datatype of one of the column lets say MNO is int identity.
3. Inserted some records into this table using SSIS. the values in the column MNO are from 1 till 20
2. i want insert more records into this table ABC using SQL task in SSIS
How do i do this. can any body help me out.

Thanks in advance

View 1 Replies View Related

Row Increment

Jun 12, 2008

1. I have a table lets say ABC in which the datatype of one of the column lets say MNO is int identity.
3. Inserted some records into this table . the values in the column MNO are from 1 till 20
2. i want insert more records into this table ABC
How do i do this. can any body help me out.

Thanks in advance

View 2 Replies View Related







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