T-SQL (SS2K8) :: Increment A Column By 5 Starting At 5

Jun 4, 2015

I am trying to increment a column that I am creating in a select by 5's, example 5, 10, 20, 25.... first row starting at 5,

Something like

WITH CTE as
(
SELECT cast(5 as int) as myColumn from table
)

SELECT cte.myColumn + 5 from CTE

View 3 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Increment String By Appending 01

Oct 27, 2014

I am having a

Source Table: #test1(studID, FIrstNAme,LasteName)

Target Table: #Test2(StudID, UserName)

Now I want to create usernames from #test1 by considering first character of first name and last name and if same combination found then append with 01.

Example if #test1 contains data as below:

1,Abhas, Pawar
2, Arun, Pawar
3, Ashis, Panday

Then i want to create username like:

apawar
apawar01
apanday02

but if same username exists in #test2 then i want to inser records as below:

first apawar will check in #test2, if not exists insert as it is:

if apawar01 exists in #test2 then, cretae apawar02 instead of apawar01

for next create apawar03 and insert and so on...

In brief I want to check created username eith #table2 and if same exists then first check if lower value available if not then create with lower value and insert.

View 5 Replies View Related

T-SQL (SS2K8) :: Group By And Order By - Location Starting With A And B

Jul 7, 2014

I am having below schema.

CREATE TABLE #Turnover (
location varchar(50),
Total int
)

insert into #Turnover (location,Total) values('A', 500)
insert into #Turnover (location,Total) values('AB', 200)
insert into #Turnover (location,Total) values('ABC', 100)
insert into #Turnover (location,Total) values('BA', 100)
insert into #Turnover (location,Total) values('BAC', 500)
insert into #Turnover (location,Total) values('BAM', 100)

Now i want output order by total but same time i want to create two groups. i.e. location starting with A and order by total and after locations starting with B and order by total.

View 5 Replies View Related

T-SQL (SS2K8) :: Write Into A Table User-entered Value And Increment That Number N Times As Existing Rows

Jun 25, 2014

I need to have a script where it ask the user for a value, the script will search for all records that match the value. Then it will display the numbers of records found and ask the user to enter a different value. The rest of the script will use this new value and increment by 1 n times as the number of records found. I started the script where it will ask for "HANDLE" and display the number of records found with that "HANDLE"

declare @HANDLE as varchar(30)
declare @COUNT as varchar(10)
declare @STARTINV as varchar(20)

set @HANDLE = ?C --This is the parameter to search for records with this value
set @STARTINV = ?C --User will input the starting invoice number
SELECT COUNT as OrderCount FROM SHIPHIST
where HANDLE = @HANDLE

I just can't figure out how to proceed to use the entered invoice # and increment by 1 until it reach the number of records found.

This will be the end results:

Count=5 --results from query
STARTINV=00010 --Value entered by user

Handle,Inv_Num
AAABBB,00010
AAABBB,00011
AAABBB,00012
AAABBB,00013
AAABBB,00014

View 9 Replies View Related

T-SQL (SS2K8) :: Generate Working Schedule For Employees For X-days Ahead Based On Starting Date

May 6, 2014

I would like to generate a working schedule for employees for x-days ahead based on a starting date that the user can enter.

I have got 3 relevant tables:

1. Table X with (1) resourcenumber, (2) starting date working schedule and (3) the daynumber representing the starting date (this is ISO so 1 for Monday, 2 for Tuesday etc.)

2. Table Y has the schedule itself and can hold a 7-days schedule or a 14-days schedule. In case of 7 days schedule there a 14 (!) records with (1) resourcenumber, (2) daynumber, (3) starting hour a.m. (4) ending hour a.m (5) starting hour p.m and (6) ending hour p.m. In case of a 14-days schedule there are 28 records (a.m. and p.m. records)

3. Table Z with resource data.

An example to clarify (for fake employee 100):

Table X:
Resource: 100
Starting date: 2012-03-01 (from this date the schedule will be effective)
Daynumber: 4 (2012-03-01 was a Thursday)

Table Y (Resource has a 14 days schedule because per 2 weeks Monday is an off-day):

Record 1 shows: Resource: 100, Daynumber: 1 (= Monday, working day), AM-Starting hour: 09:00, AM-Ending hour: 13:00, PM-starting hour: 13:30, PM-ending hour: 17:30
Record 2: same but daynumber is 2
Record 3: same but daynumber is 3 etc.
...
Record 8 shows: Resource: 100, Daynumber: 8 (= Monday, off-day), AM-Starting hour: 00:00, AM-Ending hour: 00:00, PM-starting hour: 00:00, PM-ending hour: 00:00
Record 9: same as record 2 but daynumber is 9.
etc.
...
Record 14: same as record 7 but day is 14 (= last day)

The weekend days show as 00:00 for the hours (same as day 8 in example)

I generated the working schedule with a CROSS APPLY function based on the starting date and the x-number of days ahead.

I then evaluate the actual daynumber corresponding with that date with the daynumber in table Y. That works fine with a 7-days schedule but I can't get it fixed with a 14-days schedule. Day 8 in that schedule represents an actual day 1 but how do I know what actual date day 8 is ... I think I have to start with the starting date in table X ...

I think ideally I would like to have the generated days as follows (as an example in case of a 14-days schedule starting 2014-05-01 for 30 days ahead):

2014-05-01 = day 4 (= actual daynumber)
2014-05-02 = day 5
2014-05-03 = day 6
...
2014-05-10 = day 13
2014-05-11 = day 14
2014-05-12 = day 1
2014-05-13 = day 2
2014-05-14 = day 3
...
2014-05-24 = day 13
2014-05-25 = day 14
2014-05-26 = day 1
2014-05-27 = day 2
...
2014-05-31 = day 6

With this done I can compare the actual daynumber with the daynumber in Table Y.

The rownumber that the CROSS APPLY function generates has to be reset to 1 after day 14. I tried PARTITION BY in THE ROW_NUMBER function but to no avail ... The only field I can partition by is the maximum value of the daynumber (14 is the example) but that is not allowed in the rownumber function.

View 0 Replies View Related

Cursor To Increment A Value In A New Column

Nov 24, 1999

I am trying to update a new column called "sorting", with incremented values
strating at 1 for the first row and 2 for the second and 3 for the thirsd etc......., before doing that I need the table to be sorted using three
columns. I am using a cursor but it is not working I need your help.
Thanks in advance:

CODE:

set @ordering_count=0
declare review_test_cursor cursor scroll keyset for

select oid,decision_date,ranking,sorting,decision_id
from DECISION_FLAGS
order by oid,decision_date,ranking asc

open review_test_cursor
fetch next from review_test_cursor

while (@@fetch_status = 0 )
Begin
update DECISION_FLAGS
set sorting = CAST ((@ordering_count + 1) as VARCHAR)
set @ordering_count = @ordering_count + 1

fetch next from review_test_cursor
end

close review_test_cursor
deallocate review_test_cursor

View 2 Replies View Related

Auto Increment On Non PK Column

May 2, 2008

How can I put an Auto increment on a non PK field?
for ordering contents items?

View 9 Replies View Related

Column That Is Not Set To Auto Increment

Oct 16, 2014

I have a column that is not set to auto increment "IDX and Im inserting 800 part numbers but i want the IDX column to start at IDX 400 and increment 1 time per part number that is inserted. how can i accomplished that task.

EXAMPLE:

IDX PART#

400 abcde
401 fghi
402 jklm

etc. and so forth until the last part# will have IDX 1200...

View 1 Replies View Related

Identity Column-- Seed/Increment Value

Oct 1, 1998

I have created a table that generates a sequential id and a
stored procedure that will return that id. The trouble is
no matter what I set the Seed or Increment values to, the
id will always start with #1 and increment by 1.

My table is BILLING_TIME_ID
Identity field BT_GEN_ID
(SEED 200, INCREMENT 1)

The sp is as follows:
CREATE PROCEDURE BT_NEXT_ID
AS
INSERT dbo.BILLING_TIME_ID DEFAULT VALUES
select count (*) from dbo.BILLING_TIME_ID
GO
I have double checked that Identity_Insert is set to off for
this table. (does this default to off unless it is set to on?) Since
there is only 1 field in the table, I don`t have any indexes set.

Thanks for your help!
Toni

View 1 Replies View Related

Union ALL + With Auto Increment Column??

Aug 22, 2006

Hi there,

With a Union all Query is there a way to have it also generate
an Auto Increment (number) column that is appended to the Union all results

?

View 2 Replies View Related

DTS Auto Increment Column And Excel

Feb 8, 2008

i've posted in the wrong forum, so im posting here

hi, im having problems to import data from my excel to a sql table.

in the excel file i have exact the same fields that i have in the table excepts the primary key which is an auto increment. When i try to import data, an error that i can't insert nulls into my auto increment column.

I put enable identity insert in the edit options, but still doesnt work.

can anyone help?

thanks in advance

View 1 Replies View Related

Can I Increment The Column (c1+2) ---by Creating The Trigger

Mar 10, 2006

hi,i am a beginner to ms sql server2000i have a tablecreate table ddd (a int, b int)by table structure is a bnow when i enter a value in b column suppose '2' in column bbext time when i insert a value in the column a i have to get the valuein b as 3 is thi spossible with triggersinsert into gdg values (1,2)a b1 2insert into gdg (a) values(2)a b2 3----------------> i have to get this 3 automaticallyis there any method to get thispls help mesatish

View 1 Replies View Related

Concat With Auto-increment Column

Aug 29, 2007

I have a column with consist of customer number.e.g.
c001
c002
c003

How do I add the character "c" to the auto-incremental number everything I add?

View 7 Replies View Related

Alter Column To Have Auto-increment (identity)

Oct 27, 2006

trying to change a column that is just a INT NOT NULL column, to have an auto-increment.


Code:

ALTER TABLE [ImpExpTables].[dbo].[ImpExp_eBayLocalNeedsDeleted]
ALTER COLUMN ID int IDENTITY(1,1) NOT NULL



just gives error at IDENTITY

View 7 Replies View Related

Change Increment Value For Existing Identity Column

Jul 20, 2004

Hi,
How to Change Increment Value for existing Identity Column (MS SQL2000) ?

I know how to change the seed :
DBCC CHECKIDENT (activity, RESEED,4233596)

but I need the future id generated with step 2
4233596
4233598
4233600
I would like to do it using T-sql because I will need to do it every day after syncronising with another SQL server .

Thanks,
Natalia

View 1 Replies View Related

SQL 2012 :: Create A Column Of Numbers That Increment By 1?

Feb 18, 2014

I'm trying to create a column of numbers that increment by one.

I'm not able to use a #temptable in the application I'm using so I cannot use IDENTITY(int,1,1).

I want to add an Id column to this query:

Select distinct sd.name,ic.TABLE_SCHEMA,ic.TABLE_NAME from sys.databases sd
cross join INFORMATION_SCHEMA.COLUMNS ic
where sd.name = 'ODS1stage'
order by TABLE_SCHEMA,TABLE_NAME

How can I accomplish this without creating a temp table? I would just alter the table and insert the numbers but there are 2000 rows.

View 7 Replies View Related

Change The Seed && Increment Value Of An Identity Column.

Sep 5, 2007



Dear Sir,


the following code is copied from the SQL Server Help Example.



CREATE TABLE MyCustomers2 (CustID INTEGER IDENTITY (100,1) PRIMARY KEY, CompanyName NvarChar (50))

INSERT INTO MyCustomers2 (CompanyName) VALUES ('A. Datum Corporation')

ALTER TABLE MyCustomers2 ALTER COLUMN CustId IDENTITY (200, 2)

It gives the following error.

Msg 156, Level 15, State 1, Line 3

Incorrect syntax near the keyword 'IDENTITY'




Can U please guide me abt the error.

with regards,
wilfi

View 5 Replies View Related

Transact SQL :: Key Increment Even On Failed Insert Into On One Column

May 28, 2015

The reason why cust_id started at #4 and not #1 is because I failed to insert property three times in a row for having "Tatoine" instead of "WI" or a state less than 5chars nchar(5) correct? Then when I did a valid statement, the row was created at the starting number of four. I imagine this prevents users from having duplicate cust_ids. This however is also where rollback and similar commands could be handy correct or is there something more obvious I'm missing on a failed "insert into" to not increment the cust_id. The three rows 1,2 and 3 do not exist I believe and are not null.  Having null values would of contradicted the table where two columns "not null" are a requirement.

CREATE TABLE customersnew
(
cust_idINTNOT NULL IDENTITY(1,1),
cust_nameNCHAR(50)NOT NULL,
cust_addressNCHAR(50)NULL ,
cust_cityNCHAR(50)NULL ,
cust_stateNCHAR(5)NULL ,

[code]...

View 2 Replies View Related

Strange Behaviour Of Auto Increment ID Column

Mar 15, 2007

Hi members,

I am facing a grange error, I hv an asp .net application running with sql server 2000 on a web server.

one table say tblProducts, I have few colums in it with an ID Primery Key field which is auto increment.

I have around 1500 records in it, what i am seeing is that autonumbers are not comming in sequence. it is skiping few numbers after rendom intervals.

like

1
2
3
4
5
7
9
12
13
14

like this there is no error in the code as its only a simple insert query. can anybody tell me what could be the reason.

regards

Aloha

View 3 Replies View Related

Problem With Identity Column Increment In Sql Server 2005

Jan 22, 2008

Hi
I am trying to use the identity data type ( column)
I am using examples from the book and management studio in sql server 2005.
I am using the identity property for the customer Id in customers table.I accidentatly executed the querry twice and I had two same record with different customer id numbers of 1 and 2 . I realised the problem and I had to delete the second record.
The problem is now even if I have deteted the 2nd record with customer id 2 , when I insert a new record the identity value ( customer Id) increments with a number after the value I deleted. i.e if I deleted a second row with customer id 2 ( identity 2) when I enter a new record it enters with a customer id of 3 and whenever i add a new record it increments from there.
So instead of first record have cust id 1 and second record customer id 2 etc , I get first record with cust id 1 , second record with cust id 3 , third record cust id 4 etc.
How can I get rid of this wrong values of identity values whenever I delete a record and try to add a new record?

Thanks



View 1 Replies View Related

SQL 2012 :: Update A Column With A Sequence Of Numbers Starting From 1?

Oct 7, 2015

If Exists ( Select c.name from sys.columns c where object_id = object_id('HH835HP') and C.name = 'ID_1' )
Begin
UPDATE HH835HP
SET ID_1 =
( select ROW_NUMBER() OVER(ORDER BY CHKDTS ASC) AS ID_1 FROM HH835HP ) ;
End;

Obviously... The stuff inside the IF is wrong syntax...I mean

UPDATE HH835HP
SET ID_1 =
( select ROW_NUMBER() OVER(ORDER BY CHKDTS ASC) AS ID_1 FROM HH835HP ) ;

View 4 Replies View Related

I Had Set My Windows Service's Startup Type As Automatic But It Is Not Starting Up Automatically When The System Is Starting.

May 18, 2007

Hello,



I had created a windows service using C#. I set its Startup Type as Automatic but it is not getting started automatically when my System Starts.

View 3 Replies View Related

Adding An Auto-increment Column To Existing Table With A Particular Order

Oct 19, 2005

Hello all,I'm using SS2K on W2k.I'v got a table say, humm, "Orders" with two fields in the PK:OrderDate and CustomerID. I would like to add an "ID" column whichwould be auto-increment (and would be the new PK). But, I would reallylike to have orders with the oldest OrderDate having the smallest IDnumber and, for a same OrderDate, I'd to have the smallest CustomerIDfirst. So my question is:How could I add an auto-increment column to a table and make it createits values in a particular order (sort by OrderDate then CustomerIDhere)?In the real situation, the table I want to modify has around 500krecords and the PK has 5 fields and I want to sort on three of them.Thanks for you helpYannick

View 7 Replies View Related

Select Into Statement Without Taking Auto Increment Of ID Column To The New Table

Mar 7, 2011

Due to localization I have the need to make child tables, where there is a composite Primary Key, between the Id column and the LanguageSign column. On the parent table the Id column is Identity column with auto increment.

The problem is that during the select into query to copy columns from parent to child, this auto increment behaviour of the parent-Id is copied to the child-Id. However I do not want that, because the same Id will be used by different LanguageSign entries

Is there a way to use 'select into' without copying the auto increment, or is my only option to make a whole new column without auto increment on the child and copy the records?
 
btw I have used this statement

SET
IDENTITY_INSERT MyTable

ON , so that inserting into the Id column is possible. I can see however that this does not take away the auto increment...

View 4 Replies View Related

Createing Column Primary Key And Contains Of 3 Characters And 6 Auto Increment Numbers (example: DLL - 123456) (

Dec 28, 2007

i would to make a column contains of 3 characters and 6 auto increment numbers (example: "DLL - 123456")

and made it primary key and which data type i should use. i do not know whether i use after insert trigger in two columns one for three characters and another for code which has identity property >>>so please help me

View 4 Replies View Related

T-SQL (SS2K8) :: Cannot Define Primary Key Constraint On Nullable Column But Column Not Null

Sep 30, 2014

We have a database where many tables have a field that has to be lengthened. In some cases this is a primary key or part of a primary key. The table in question is:-

/****** Object: Table [dbo].[DTb_HWSQueueMonthEnd] Script Date: 09/25/2014 14:05:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DTb_HWSQueueMonthEnd](

[Code] ....

The script I am using is

DECLARE@Column varchar(100)--The name of the column to change
DECLARE@size varchar(5)--The new size of the column
DECLARE @TSQL varchar(255)--Contains the code to be executed
DECLARE @Object varchar(50)--Holds the name of the table
DECLARE @dropc varchar(255)-- Drop constraint script

[Code] ....

When I the the script I get the error message Could not create constraint. See previous errors.

Looking at the strings I build

ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] DROP CONSTRAINT PK_DTb_HWSQueueMonthEnd
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] Alter Column [Patient System Number] varchar(10)
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] ADD CONSTRAINT PK_DTb_HWSQueueMonthEnd PRIMARY KEY NONCLUSTERED ([Patient System Number] ASC,[Episode Number] ASC,[CensusDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

They all seem fine except the last one which returns the error

Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'DTb_HWSQueueMonthEnd'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

None of the fields I try to create the key on are nullable.

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

Difference In Starting Rep Service Vs. Stopping And Starting The Rep Job?

Feb 1, 2007

When our rep distribution services time-out (several times a day) some dba's just restart the service while others restart the rep job which starts the service. Are there any differences between these two methods? Does restarting the service inherit any changes made to the job's attributes?



Thanks!

View 1 Replies View Related

T-SQL (SS2K8) :: Replace Column With Another Column When It Does Not Exist

Jun 24, 2014

I have a script that loops through a series of tables to send data to a table from each of the tables. My issue is that not all tables have the columns I need in them. What I would like is to replace the column with another column when it does not exist. Something like below

Select Misisng_Column(A.Name, replace with B.Name) as Name
FROM SomeTable A
Cross Join (Select Name FROM AnotherTable) B

AnotherTable has one record in it. To avoid a Cartesian issue. Like I said just an example

In my real script the table aliased as A is from a list of tables in a sys.tables query that loops through to the end.

View 2 Replies View Related

SQL Agent Is In Starting Status - But Not Starting

Mar 6, 2002

We have SQL 2000 (SP2) , Our SQL server agent showing green light as started from EM , It is succussfully restarting from NT Services too . But When I open the properties of the jobs from EM its gives error message SQL DMO error " SQl Agent is starting , try later " . And in EM Next run Date & Time not available .

MDDB database is accessable & in Log file its recovered fully

Thankx in Advance

Sha

View 1 Replies View Related

T-SQL (SS2K8) :: Use Previous Month Data In Column As Following Months Data Different Column

Aug 20, 2014

I have a table with Million plus records. Due to Running Totals article, I have been able to calculate the Trial_Balance for all months.

Now I am trying to provide a Beginning Balance for all months and the Logic is the Beginning Balance of July would be the Trial_Balance of June. I need to be able to do this for multiple account types. So the two datasets that need to be included in logic is actindx and Calendar_Month.

For actindx of 2 and Calendar_Month of 2014-01-01The Trial_Balance_Debit is 19585.46 This would make the Beginning_Balance of actindx 2 and Calendar_Month of 2014-02-01 19585.46

I am trying to do some type of self join, but not sure how to include each actindx number differently.

Table creation and data insert is below.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TrialBalance](
[Trial_Balance_ID] [int] IDENTITY(1,1) NOT NULL,

[Code] ....

View 7 Replies View Related

T-SQL (SS2K8) :: Pipe Row To Column

Mar 4, 2014

Sample Data

MemberID Codes
00000123 012|222|123|333
00000233 012|222|332
00000244 012|211
00000332 012

I am trying to get it so as following:

MemberID Code1, Code2, Code3, Code4

I tried using the XML method but in working with an example, I actually got stuck on one of the declare fields and cant seem to work around it.

Failed Attempt:
DECLARE @x xml;
DECLARE @line VARCHAR(MAX);
SET @x = Cast(
'<field>'
+ replace(@line, '|', '</field><field>')
+ '</field>' AS XML);

[code]...

View 6 Replies View Related

T-SQL (SS2K8) :: CTE Update Column

Oct 24, 2014

With cte_table (columna)
As (select a from cust)
Update columna
Set a = 'hello'

Question: would a in cust be updated even though the update is to the CTE column named columna? Or would there be an error where the column name must match?

View 2 Replies View Related







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