T-SQL (SS2K8) :: Add Auto Incrementing Column To SELECT Statement

Apr 1, 2013

Along with the data that I am pulling back from query, I also need to provide an ImportID column with the following requirements:

YYMMDDGP0001, YYMMDDGP0002, YYMMDDGP0003, and so on. The 0001, 0002, and 0003 part could get big into the hundreds of thousands.

I have the YYMMDDGP part down with the following expression:

SELECT CONVERT(VARCHAR(6), GETDATE(), 12) + 'GP' AS [ImportID]

Now I need to get the Auto Incrementing number part of this. I have been researching this trying SELECT INTO a temp table using the Identity Function and declaring different variables all with no luck.

View 7 Replies


ADVERTISEMENT

Identity / Auto Incrementing Column

Feb 16, 2006

Hi,
I have an auto incrementing int column setup which serves as my unique primary key.  Just wondering what happens when the auto increment reaches the limit?  Will it recycle numbers from the begining (who's rows have obviously been deleted by this stage)?

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

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

T-SQL (SS2K8) :: Pass A Column Name Using Parameter In Select Statement

Sep 5, 2014

I have a temp table that hosts data from a MDX query, I want to select a column from that table by passing in a parameter and then insert to a new table.

Here's the table structure, let's call it #temp

[Product].[Product Hierarchy].[level 03].[Member_CAPTION], [Measures].[Gross Sales]
Bike, 200
Accessory , 100

I have a table in the DB created as [ProductSales]

Here's what works for me:

insert into [ProductSales](Product, Sales)
Select convert(varchar(20), "[Product].[Product Hierarchy].[level 03].[Member_CAPTION]") as 'Product' , convert(decimal(18,2), [Measures].[Data]) as 'Sales'
From #temp

But in reality the product level is not always on level 03, I want to define a parameter @Product and pass it to the select list.

Here's what I tried to do:

Declare @Product varchar(500) = convert(varchar(20), "[Product].[Product Hierarchy].[level 01].[Member_CAPTION]")
Declare @SQL varchar(MAX)
SET @SQL='insert into [ProductSales](Product, Sales)
Select '+@Product+' as 'Product' , convert(decimal(18,2), [Measures].[Data]) as 'Sales'
From #temp'
Exec @SQL

But it threw me error, what is the right way to do it, is it because the double quote or single quote thing?

View 1 Replies View Related

T-SQL (SS2K8) :: Get Script To Output Only 2 Decimal Places For Amount Column From Select Statement?

Jul 22, 2015

I have a routine that generates an HTML email and sends it just fine, but one of the columns ends up with 4 decimal places for a column datatype of money. How can I get the script to output only 2 decimal places for the amount column from the select statement?

Here's the script:
declare @tableHTML nvarchar(max) ;
set @tableHTML =
N'<h1>Revenue Report</h1>' +
N'<table border="1">' +
N'<tr><th>Amount</th><th>Index</th><th>CompObj</th><th>Rev Type</th><th>Program</th>'+
CAST ((SELECT td=SUM(dbo.tblAllocations.Amount),'',

[code]....

View 2 Replies View Related

Auto Incrementing

Nov 14, 2007

Hi

I'm using a insert into fuction kind of like below

INSERT INTO table1(

col1
col2
col3
col4
)
SELECT

col2
col3
col4

FROM ...............

I'd like to auto-increment col1 so it counts how many rows are being added


any help is very appreciated

View 5 Replies View Related

How To Set Up Auto Incrementing For A Field

Aug 10, 2006

 
I have a database table. I need to set a particular data field to allow for Auto Incrementing. Basically I need to set up the initial integer value to start at. Then to specify the amount to increment by.
What I have done so far is to right click on the field name in SQL Server 2005. Then, on the pop-up menu I select the menu option for properties.
When the properties are displayed I see some fields listed in dark grey but I am not able to edit these fields. In other words, if I try to type text in this field, nothing happens. The fields I am talking about are:
Identity Increment
Identity Seed
Is Identity
Does anyone know what the problem is? What do I have to do to edit these fields.
 

View 2 Replies View Related

Unwanted Auto-incrementing

Aug 17, 2006

Here is a simplified version of my problem:
I am inserting data into a table using a stored procedure. The table has an identity column that increments with each insert. When I use erroneous data in the other fields the insert fails….no surprises there! But when the next insert occurs with valid data I find that my identity field has increased even with those inserts that failed, so my sequence has jumped a few numbers. How do I get the identity inserts to roll back if the rest of the data in a row doesn’t insert successfully?
Marcha x

View 9 Replies View Related

Auto-incrementing A Field

Nov 9, 2006

I am porting a database from Informix to SQL Server 2000. Several fields in the informix database are specified as SERIAL, which means that they auto-increment auto-magically if you insert a 0 into them. Well...I was looking for an equivalent in SQL Server 2000, and thought I had found it in the IDENTITY column concept.

With further investigation into IDENTITY columns, however, I discovered that only one column per table can be given the IDENTITY property. Why is this? Is there a way around that? If not, is there another way to achieve this feature in SQL Server 2000? If not, any suggestions on how I can do it?

Thanks!

Lisa

View 5 Replies View Related

Identity Value Not Auto Incrementing

Feb 19, 2008

My Identity value column is not autoincrementing, its seed is set to 1, and increment set to 1.
yet when i click the auto generated 'Add New Record' button in the BindingNavigator control set (in a form where it is populated with databound text boxes), this Identity column is not auto incremented?


And if i try to write a value to this column, i get the error telling me this column cannot be written to. Yet if i do not write to it, then i get "This column does not allow nulls"

To load my data i am using:




Code Snippet
'clear dataset
Me.DsQuote.Clear()
'fill the datagrid with data from tblQuoteID
Me.TblQuoteIDTableAdapter.Fill(Me.DsQuote.tblQuoteID)






and to save data im using:




Code Snippet
Me.Validate()
'end data edit
Me.TblQuoteIDBindingSource.EndEdit()
'update the dataset with table data
Me.TblQuoteIDTableAdapter.Update(DsQuote.tblQuoteID)


anything im doing wrong? this data is being viewed in a datagrid btw.

cheers

View 1 Replies View Related

Generating Auto Incrementing No Using SQL Query

Sep 22, 2004

Hi everyone,

I am having a table with which i generate a report. Now how to using a SQL query i can generate a auto incrementing no.

Say i am executing this query

SELECT NAME,AGE,ADDRESS FROM MEMBER which gives

NAME AGE ADDRESS
HOLYMAC 13 MALACCA
HOLYCOW 25 USA
HOLYGOD 55 LONDON


Now how can i make it come out like this

SNO NAME AGE ADDRESS
1HOLYMAC 13 MALACCA
2HOLYCOW 25 USA
3HOLYGOD 55 LONDON

See the first column is a auto incrementing number 1,2,3.


How can I write a SQL QUERY that outputs a auto incrementing number.


Thank you
Have nice day

View 2 Replies View Related

Re:- Auto-incrementing An Alphanumeric Field

Jul 13, 2001

Hi

Everyone

I have a problem my table structure is like this

book_id varchar2(30)
book_name varchar2(30)


Now i want to enter the data into the fields like this

B001 Java Unleashed
B002 ASp Unleashed


and so on

So my Problemis how i will auto increment the book_id field though that is an alphanumeric field.

PLease help me that how i will insert and select from this table


Waiting for your help


Manish

View 1 Replies View Related

Auto-incrementing With Leading Zeros

Aug 10, 2006

Hi All,
I need to set up a kind of identity insert that gives an output in the format: 00001, 00002, 00003 etc. Is there a formatting option for this sort of output using normal identity insert features or do I need to write a function to insert these values (perhaps as text) each time a new record is created?
Sorry if this is really simple but it's only my 4th day in this job!
Marcha

View 5 Replies View Related

Transact SQL :: Primary Key Auto Incrementing By 1000 Instead Of 1

Jul 13, 2012

We have upgraded our SQL 2008 server to 2012 last month.  i've noted since then that many tables that have auto increment primary key bigint field increases by 1 like it should, then for some reason it jumps up by 1000 or even 10000?  i have seed adn auto increment set to 1 but doesnt effect it.  Is there anything that could be causing the next value to jump that much?

View 18 Replies View Related

Replication In Database Having Auto Incrementing Field

Aug 31, 2007



Hi,

If i were to replicate a database with another where in both the databases have an auto incrementing field. What could be the problems that's goin to arise out of it. How to deal with such a scenario...?????

View 6 Replies View Related

Auto Export Select Statement?

Mar 1, 2013

i'm using ms sql server 2008 r2 advanced express.

i have a select statement that generates my google shopping feed.

is there a way to get this statement run automatically and export the results to a tab delimited csv file?

i'm currently using an asp script to create an xml file for the feed, but it's putting too much strain on the server.

View 10 Replies View Related

Auto Incrementing-&>Updating Values In Two Related Tables :Help!!!

Nov 11, 2005

hi there,
 i am new to sql server database.i am doing small projects right
now using asp.net and sql to create webpages (very basic webpages)
My problem is:

Problem :
 
   i have two tables .....table 1 and table 2.
                   
                   
                   
    Table 1 has following fields: studentid,student name,student address.
                                                               
Table 2 has following fields:studentid and course .
  table1 student id is the primary key refrencing table 2 student id.
Now i delete a record in table 1 which will in turn also get deleted in
table 2 . so for eg  if i have three records 1 ,2 and 3 ....then i
delete 2 in table 1 ...i will have 1 and 3 in both table 1 and table
2....now i want 3 to become 2 in both table 1 and table 2...so that i
dont have empty space between two student id's 1 and 3. so this is my
problem....if any one can help me out with suggestions please
do.  
                                                                                 
thank you all........
                                                                                                           
     ahmed_ind

View 4 Replies View Related

Set Custom Identity Keys For Master Tables(auto-incrementing):

Jun 17, 2007

I need some help for designing the IDs / Primary keys for some master tables in my database. Following are master tables. Client_Master, Buyer_Master & Seller_Master; I want to set Client_Id, Buyer_Id & Seller_Id as their respective primary keys and they should have following properties

Client_Id :- a) should be auto-incrementing value, b) unique & c)should be of the format – CLXXXXXX, where “CL” {Constant start characters} & “X” {any number 0-9}
Similarly::
Buyer_Id :- BYXXXXXX
Seller_Id :- SLXXXXXX

We are implementing the database in MS-SQL 2005 & MySQL

Can anyone help me find a solution to this, especially in MS-SQL.

View 2 Replies View Related

SQL Server 2012 :: Auto Incrementing Alphanumeric Field In Table

Oct 1, 2014

I need to auto increment an alphanumeric field in a table.

The process is as follows:

1. First position is static letter C for contact or static letter A for account - field contact_id
2. The following 6 positions are numeric - example of the string would be C004658
3. When new contact is entered, it should look up the highest numeric value (in this case 004658) and increment it by one - resulting in C004659

View 9 Replies View Related

DB Design :: Auto Selections While Coding Using Select Statement

Aug 25, 2015

enable or shortcut key for Auto Database or Table View while coding. When I wrote sample code like below

SELECT * FROM VENKAT.

When I type V then I need to know there is Venkat Database with pop Message below.

View 2 Replies View Related

T-SQL (SS2K8) :: How To Execute SP In Select Case Statement

Mar 20, 2014

I am a junior dba not a developer. So I'm just trying to get use to write code in T-SQL.

Anyways, I have a table which is dba.dbhakyedek.

Columns are

dbname, username, class_desc, object_name, permission_name, state_desc

I have statement

select case
when class_desc='OBJECT_OR_COLUMN' then 'GRANT '+permission_name+' ON '+'['+left(object_name,3)+'].'+'['+substring(object_name,5,len(object_name))+ '] TO '+username
WHEN class_desc='DATABASE_ROLE' THEN EXEC sp_addrolemember N'object_name', N'MC'
end
from dba.dbhakyedek
where username='MC'

This statement was running successfully until exec sp_addrolemember thing. I just learned that i can't call a sp in select case but i couldnt figure out how to do it.

View 6 Replies View Related

T-SQL (SS2K8) :: Select Statement That Needs To Use Custom Grouping

Aug 10, 2015

I am trying to SELECT data based on custom groups of that data. For example and in its simplest form:

SELECT COUNT(*)
FROMdbo.People
WHERE Current_Status = ‘A’
GROUP BY People_Code

The People_Code is the difficult part. The code represents the building that they work in. However, some buildings have multiple People_Codes. Kind of like multiple departments within a building.

For example:

Building NamePeople_CodeEmployee Count
Building A617535
Building B985665
Building C529212
Building C529932
Building C419816
Building D326974
Building D781024
Building E25365

Each building has a main People_code which, for this example, could be any one of the codes for the building. For example: Main code for building C can be 5292 and for building D it can be 7810.

Applying a variation (which is what I cannot figure out) of the SELECT statement above to this table, the result set for Building C must be the combined employee count of all three People_codes and must be represented by the main code of 5292 as a single row. Building D would have a row using code 7810 but will combine the employee count of codes 7810 and 3269.

I built a conversion table that would match up the main code with all of its related codes but just couldn’t seem to make it dance the way I want it to.

People_CodeNameGroupNameGroupPeopleCode
6175Building ABuilding A6175
9856Building BBuilding B9856
5292Building CBuildingCGroup5292
5299Building C AnnexBuildingCGroup5292
4198Building C Floor6BuildingCGroup5292
Etc…

The whole query is much more involved than just the simple SELECT statement used here, but if I can get this to work, I’m sure I can apply it to the full query.

View 5 Replies View Related

T-SQL (SS2K8) :: Getting Records In N-Relation Table In One Select Statement?

Jun 9, 2014

I have 2 tables in a 1: n relation. How can i get a select statement that the field in the n-relation with outputs, separated by a semicolon; Example: One person have many Job Titles

Table1 (tblPerson)
Table2 (tblTitles)
1, "John", "Miller", "Employee; Admin; Consultant"
2, "Joan", "Stevens", "Employee, Software Engineer, Consultant"
and so on .... 1 in select statement:

View 1 Replies View Related

T-SQL (SS2K8) :: Select Statement With Derived Order Status

Aug 28, 2015

Here is my requirement

Table 1 Order
order ID, Sales order ID order date, order type

Table 2 Order details
Order Details ID, Order ID, Order Stage

Table 3 Related Order details
Order ID(FK to Order ID), Related Order Details ID(FK to Order Details ID), Related Order ID( FK to Order ID)

Here is example

Table 1 Order
1, 1234, 2015-01-01, Refill
2, 1234, 2015-02-02, Extension

Table 2 Order Details
1, 1, Approved
2, 1, Approved
3, 2, Rejected

Table 3 Related Order Details
2, 1, 1
2, 2, 1

I have to Select Order, Order Details and Order Status

Order Status is determined from Order Stage as follows:

If, at least one order detail line(from Order Details and Related Order details table) is approved, that Order status=Approved.

For the example, Order Status of Order ID=2, is Approved based on order status for order details lines 3(from table 2) and order details ID 1 and 2 (from table 3)

How to combined order stage from table 2 and table 3 and then compute order status.

View 3 Replies View Related

T-SQL (SS2K8) :: Stored Procedure And SELECT Statement Return Different Results

Dec 4, 2014

I have a stored procedure on a SQL Server 2008 database. The stored procedure is very simple, just a SELECT statement. When I run it, it returns 422 rows. However, when I run the SELECT statement from the stored procedure, it returns 467 rows. I've tried this by running both the stored procedure and the SELECT statement in the same SSMS window at the same time, and the behavior is the same. The stored procedure is:

USE [REMS]
GO
/****** Object: StoredProcedure [mobile].[GetAllMobileDeviceUsers] Script Date: 12/04/2014 */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] ....

When I do this in the same SSMS window:

exec mobile.GetAllMobileDeviceUsers

SELECT
ee.EmployeeID,
EmployeeName = LastName + ', ' + FirstName
FROM EmployeeInvData ee
--UNION

[Code] ....

I get two result sets. The first is 422 rows; the second is 467 rows. Why?

View 4 Replies View Related

T-SQL (SS2K8) :: Dynamic Column Names For Insert Statement?

Apr 9, 2015

I would like to provide the names of columns in an insert statement from a schema table, so that when running through a number of Bus Rule checks I can reference the schema table and only maintain the columns in the schema table rather than maintain named columns in multiple insert statements. So my query for one check looks like below. I'm using dynamic sql to execute the insert statement. My question is, is there a better way or different way to do this without using dynamic sql? Ie, Is there a way that I can use the columns parameter like this instead?

Insert
('+@columns+',KickoutID) Values('+@columns+',1);

Dynamic code:

Declare @columns as nvarchar(max);
Declare @InvSQL as nvarchar(max);
SELECT @columns =
STUFF ((
SELECT ', [' + name + ']'
FROM syscolumns WHERE id = OBJECT_ID('dbo.table_pvt')

[Code] ....

View 8 Replies View Related

T-SQL (SS2K8) :: Select Only Rows With Alphabetical Character In Column?

Apr 17, 2014

i am working on a small project, that I have found that someone is storing a float as a varchar(). But there are also some actual words in the same column.

I am trying to determine how I can select only the rows with alphabetical characters in that column.

Some of the data is:

1.5008e+015
1.54453e+015
1.51922e+015
1.51922e+015
1.52243e+015

but there is a mix of alphabetical characters in there as well.

1.51922e+015
1.53122e+015
FMCIT
ABCNP
FMCPNG
1.62073e+015
1.6127e+015

I want to be able to select the rows with only the alphabetical characters. There is a huge mix, and I am assuming that every first letter is one of the 26 alphabetical character used. How can I write a query to use a REGEX to select any and all rows that cannot be CAST as a Float? I have nill to no experience using REGEX.

View 9 Replies View Related

T-SQL (SS2K8) :: How To Select Rows Based On One Distinct Column

Apr 18, 2014

--------------------------------------------------
SalesOrder-ItemName-Price-Category
-------------------------------------------------
01-Camera-100-Electronic
01-Memory-4GB-10-Memory
01-Battery-5-Battery
02-Keyboad-10-Accessories
02-Mouse-5-Accessories
03-CPU-300-Hardware
03-Motherboad-400-Hardware

From above rows i would like to select rows based on one distinct column SalesOrder, i want output like below.

-----------------------------------
SalesOrder-ItemName-Price-Category
-----------------------------------
01-Camera-100-Electronic
02-Keyboad-10-Accessories
03-CPU-300-Hardware

CREATE TABLE Table1 (SalesOrder varchar(10), ItemName VARCHAR(100), Price INT, Category VARCHAR(100))

[Code] ......

View 2 Replies View Related

Using Column Number Inplace Of Column Name In SQL Select Statement

Jul 20, 2005

Hello All,Is there a way to run sql select statements with column numbers inplace of column names in SQLServer.Current SQL ==> select AddressId,Name,City from AddressIs this possible ==> select 1,2,5 from AddressThanks in Advance,-Sandeep

View 1 Replies View Related

Incrementing Column

Feb 28, 2008

Hi,

Im not sure if this can/should be done through sql...but i have a sql statement and i need the first column returned to start at 1 - and then increment for each row.

I am then using the returned values in another app.

I tried using count(columnname) but this just stays at 1 for each row.

Thanks for an feedback...

View 5 Replies View Related

How Do I Update A Column To Be Incrementing Each Row By 1

Apr 2, 2008

I have a temp tbl and in col1 row1 i would like to have 1, col1 row2 value 2, col1 row3 value 3 and so on. how can i do this?

View 3 Replies View Related

Column With Select Statement

Sep 24, 2006

Hi, i have a doubt, can a column have the value of a select? I mean, i'm making a photo gallery and on the categories table i need to know how many photos i have, so i need to count in the table photos the ones associated with the id of the category, the problem is that i'm listing categories with a datalist, is there a way so that a column on the categories table have the result of the count? Thanks in advance, if you don't understood my question feel free to ask me again and i'll try to explain it better, i really need this. 

View 1 Replies View Related







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