Reset Identity Column Value in SQL Server depending on whats being inserted
I have a SQL Server 2008 database with a table that has an ID field that has an identity increment and seed of 1.
This work great as each new record created automatically gets a new and distinct number.
Now when I insert certain new records I need to be able to make that value start at 10001 and then the next would be 10002 etc.
But this is only for certain inserts.
Is there a way to control the identity seed & increment on the fly via a query maybe?
So some inserts would follow 1,2,3,4,5,6,7 depending on whats being inserted
and others would follow 10001,10002,10003 depending on whats being inserted.
is this possible?
Make it a different field. Don't mess with your PK.
Make sure you have a plan for when you get 10000 records in this table.
Similar Messages
-
Problem in EOImpl.doDML() ,with Identity column in MS SQL server.
Hello,
I'm using JDeveloper 11.1.1.4.0
My application is working with MS SQL Server.
One of the tables in the database has its PK as Identity column.
EO is created with the corresponding attribute as Primary Key.
Upon calling doDML() in EOImpl, it generates an insert statement and attempts to insert in the PK field as well. MS SQL does not allow insertion in PK field and throws exception.
I tried setting some configuration on EO PK attribute, but in vein. Also there is no other 'unique' column in table that can be setup as PK in EO.
Appreciate your suggestions.
Regards,
Amari think better to Oracle datbase as I am afraid of that Oracle won't be able to see your problem against sql server due to sql server is not their product!
-
Performance operations based on Column values in SQL server 2008
Hi ,
I have a table which consist of following columns
ID Formula
Values
DisplayValue
1
a*b/100 100*12/100
null
2
b*c/100
12*4/100
null
I want to perform operation based on column "Values" and save data after operations in new column Name "Display Value" .i.e I want to get the below result . Can anyone please help.
ID Formula
Values
DisplayValue
1
a*b/100 100*12/100
12
2
b*c/100
12*4/100
0.48
Thanks for the help.
Regards, Priti ATry this,
create table #mytable (ID int,Formula varchar(10), [Values] varchar(10), DisplayValue decimal(10,4))
insert into #mytable values(1 ,'a*b/100','100*12/100',null)
insert into #mytable values(2 ,'b*c/100','12*4/100',null)
declare @rowcount int=1
while @rowcount <= (select max(id) from #mytable)
begin
declare @expression nvarchar(max)
select @expression=[values] from #mytable where id = + @rowcount
declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression
declare @result decimal(10,4)
exec sp_executesql @sql, N'@result decimal(10,4) output', @result = @result out
update #mytable set DisplayValue= @result where id = @rowcount
set @rowcount=@rowcount+1
end
select * from #mytable
Regards, RSingh -
Hi ,
Ident_Current('TableName') is not giving last inserted identity Value in SQL Server 2012.
Latest Value of ID and Ident_Current is differing for that particular table.
Why its happening? Ident_Current value is greater than last inserted ID.
Please guide me why its happening?Here is one example:
CREATE DATABASE PMCtest ON (NAME = 'PMCtest', FILENAME = 'B:\ProdDB-Unzipped\PMCtest.mdf', SIZE = 25GB )
LOG ON (NAME = 'PMCtest_log', FILENAME = 'B:\ProdDB-Unzipped\PMCtest.ldf', SIZE = 2GB)
CREATE TABLE identity_crisis (a int IDENTITY NOT NULL PRIMARY KEY,
b sysname NOT NULL CHECK (b <> 'sysschobjs'))
go
INSERT identity_crisis (b) VALUES ('First name')
INSERT identity_crisis SELECT name FROM sys.objects
go
SELECT MAX(a), ident_current('identity_crisis')
FROM identity_crisis
go
DROP TABLE identity_crisis
Because the second INSERT statement fails, the identity values from 2 to 12 are lost. This is a very intentional design to promote high concurrency. If you don't want gaps, you should not use IDENTITY, but roll your own.
Also, beware that ident_current returns database-wide value, so if you insert one row, and another process inserts another row before you interrogate ident_current, you will get the id for the row of the other process.
Erland Sommarskog, SQL Server MVP, [email protected] -
How to update the identity_column value in sql server 2008
Hi Team,
I have identity column based table. In the table i use insert the name as per the requirement and for ID i use to set the identity now i need to update the particular row id.
when i use to trying i'm getting the below error.
Msg 8102, Level 16, State 1, Line 4
Cannot update identity column 'CategoryID'.
Kindly help me out regarding this.
Thanks & Regards,
Ramesh RYou cannot update an IDENTITY column. You need to move the data into another table make the changes over there and insert the back the data into original table.
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to export data with column headers in sql server 2008 with bcp command?
Hi all,
I want know "how to export data with column headers in sql server 2008 with bcp command", I know how to import data with import and export wizard. when i
am trying to import data with bcp command data has been copied but column names are not came.
I am using the below query:-
EXEC master..xp_cmdshell
'BCP "SELECT * FROM [tempdb].[dbo].[VBAS_ErrorLog] " QUERYOUT "D:\Temp\SQLServer.log" -c -t , -T -S SERVER-A'
Thanks,
SAAD.Hi All,
I have done as per your suggestion but here i have face the below problem, in print statment it give correct query, in EXEC ( EXEC master..xp_cmdshell @BCPCMD) it was displayed error message like below
DECLARE @BCPCMD
nvarchar(4000)
DECLARE @BCPCMD1
nvarchar(4000)
DECLARE @BCPCMD2
nvarchar(4000)
DECLARE @SQLEXPRESS
varchar(50)
DECLARE @filepath
nvarchar(150),@SQLServer
varchar(50)
SET @filepath
= N'"D:\Temp\LDH_SQLErrorlog_'+CAST(YEAR(GETDATE())
as varchar(4))
+RIGHT('00'+CAST(MONTH(GETDATE())
as varchar(2)),2)
+RIGHT('00'+CAST(DAY(GETDATE())
as varchar(2)),2)+'.log" '
Set @SQLServer
=(SELECT
@@SERVERNAME)
SELECT @BCPCMD1
= '''BCP "SELECT
* FROM [tempdb].[dbo].[wErrorLog] " QUERYOUT '
SELECT @BCPCMD2
= '-c -t , -T -S '
+ @SQLServer +
SET @BCPCMD
= @BCPCMD1+ @filepath
+ @BCPCMD2
Print @BCPCMD
-- Print out below
'BCP "SELECT
* FROM [tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername'
EXEC
master..xp_cmdshell
@BCPCMD
''BCP' is not recognized as an internal or external command,
operable program or batch file.
NULL
if i copy the print ourt put like below and excecute the CMD it was working fine, could you please suggest me what is the problem in above query.
EXEC
master..xp_cmdshell
'BCP "SELECT * FROM
[tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername '
Thanks, SAAD. -
hello frnds,
i want to insert bit value into sql-server 2000... using hibernate
what is the datatype for java bean.... ?
and how it is mappend in mapping xml....?
if any one has idea then please help me...
thanx in advance..
regards
PanDev84The WPF MediaElement (unlike Silverlight's) doesn't support setting the Source to a Stream directly. You could try any of the workarounds suggested here:
http://stackoverflow.com/questions/7117589/using-mediaelement-to-play-video-from-stream
Othwerwise you could select the data (bytes) from the database into a byte[]:
http://stackoverflow.com/questions/13952261/insert-and-retrieve-bytearray-from-sql-server-in-c-sharp
...and then save the data to a temporary physical file and play this one as usual:
byte[] data = ...; //select from db
System.IO.File.WriteAllBytes("temp.wav", data);
var mediaPlayer = new MediaPlayer();
mediaPlayer.Open(new Uri("temp.wav", UriKind.Relative));
mediaPlayer.Play();
The MediaPlayer.Open method will read the file via a stream automatically.
Hope that helps.
Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question. -
In SQL Server Transactional replication what all changes I can do on subscriber table
In SQL Server Transactional replication what changes I can do on subscriber table
ThanksHi Ajay.G,
According to your description, if you want to do some updates at the Subscriber, you need to note the following things.
•If TIMESTAMP or IDENTITY columns are used, and they are replicated as their base data types, values in these columns should not be updated at the Subscriber.
•Subscribers cannot update or insert text, ntext or image values . Instead, you could partition the text and image columns into a separate table and modify the two tables within a transaction.To update large objects at a Subscriber, use the
data types varchar(max), nvarchar(max), varbinary(max) instead of text, ntext, and image data types, respectively.
•Updates to unique keys (including primary keys) that generate duplicates and then they are not allowed and will be rejected because of a uniqueness violation.
•If the Subscriber database is partitioned horizontally and there are rows in the partition that exist at the Subscriber but not at the Publisher, the Subscriber cannot update the pre-existing rows.
For more information, see: Updatable Subscriptions for Transactional Replication
Regards,
Sofiya Li
Sofiya Li
TechNet Community Support -
Storing 6 millions values in SQL server columns
Hi,
How many values (size) I can store in single SQL server column.
My Scenario,
Column1 Column2 Column3
1 ABC 1,2,3,........(6 millions values)
2 CDE 1,2,3,.......(6 millions values)
and problem is that I can't store them in rows. I need to store them in single column with comma separated.
What would be the best way to store them and retrieve them faster. I am thinking about converting it to byte[] or something but not sure how much time it will take to convert to byte and then again to text.and problem is that I can't store them in rows. I need to store them in single column with comma separated.
No you don't! Unless, that is, you really like to hurt yourself. It's a basic idea that in a relational database that each cell holds an atomic value, and this what relational datbases are optimised for.
That said, if all you want to do is to store a bunch of values that you will never look at in the database, but the database will act as an unintelligent data store you will only look at the values outside the database, then it
could make sense. However, a warning: just because you think that there is no requirement today, don't be surprised that you are sooner or later are asked questions like: "which the highest value for ABC?", "Which value is the most
frequent across ABCs and CDEs?". Questions that are very simple to answer is you have data in a properly designed data model. But extremely to painful to answer if your all values in a single column.
But if you take this, path, yes, storing values in a varbinary(MAX) with four bytes (or whatever that is needed) per value would be the best thing. It takes up less space than a string, and with fixed length it's easier to find value 198713 if this would
be nedded. You seem to be worried about conversion from byte to text. Why is not clear to me, since number are usally born binary. But obviously, I have no idea where you get these values from or how you would use them.
My initial recommendation still stands: store each value in a single row.
Erland Sommarskog, SQL Server MVP, [email protected] -
Identity Field in MS SQL Server
Hi All,
I'm new in JDBC. I'm trying to get the autogenerated value from an identity column in SQL Server, after an INSERT operation.
I was looking around and I found there is an smart way:
stmt.executeUpdate(str, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
but the executeUpdate reports an UnsupportedOperationException.
I'm using jdbc-odbc-bridge.
What am I missing?
thanks in advance
arturo>
but the executeUpdate reports an
UnsupportedOperationException.
I'm using jdbc-odbc-bridge.
What am I missing?Your driver does not do that. -
How to track only one column updated in SQL Server 2012?
Is there a way to only track one specific column named Newsletter (bit format) of a table only when any record in that column has been changed from False to True?
e.g. In SQL Serer 2012, I have a table named tblSignupHistory. so i originally set the query like this:
ALTER TABLE tblSignupHistory
ENABLE CHANGE_TRACKING
WITH(TRACK_COLUMNS_UPDATED = ON)
and in my stored procedure, if any data is changed, SQL Server will automatically send me an email notification.
BUT i only want the notification email to be send only when this one specific column's value is changed from 0 to 1 (False to True). Any changes in other columns for the same table can be ignored.
Thanks.Blog on the topic:
http://www.exacthelp.com/2012/03/send-email-when-data-of-any-columns-of.html
QUOTE: "Over all idea
1. Enable the change tracking (CT) in database
2. Enable the change tracking (CT) in table
3. Enabled and configure the database mail
4. Create a stored procedure which will get data change using CT and send an email
5. Create a sql sever agent job which will execute the procedure in every 10 second.
Alternate solutions blog on the topic: Get an alert when a certain record changes in SQL Server
SQL Server UPDATE() function:
http://technet.microsoft.com/en-us/library/ms177523.aspx
Kalman Toth Database & OLAP Architect
Free T-SQL Scripts
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Date column in OBIEE-SQL Server
Hi expert,
I have created date (datetime)column in sql server cube. Now I wat it inmy OBIEE as date. how to do that.
When we import,there are only three option->Double,Varchar,Unknown.Something wrong.... once you import table in rpd the column should have Type as DATETIME or DATE.
If its not the case then you can change the format in rpd.
If helps pls mark -
BCP - Error with column text in sql server 2000
Hi,
Im trying to restore a bcp using the command:
bcp "db.dbo.tb_log_old" in "tb_log2013.out" -SSERVER -T -n
Im using SQL 2000 with the table below
CREATE TABLE [dbo].[tb_log_old](
[cd_id] [int] NULL,
[cd_servico] [int] NULL,
[dt_ocorrencia] [datetime] NULL,
[nm_xml_entrada] [text] NULL,
[nm_xml_saida] [text] NULL,
[dt_inicio_processamento] [datetime] NULL,
[dt_fim_processamento] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
I have got the error
Starting copy...
SQLState = S1001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Memory allocation failure
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Text column data incomplete
SQLState = 37000, NativeError = 4810
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Expected the TEXT token in data stream for bulk copy of text or image data.
BCP copy in failedI tried with binary and nvarchar but I got the error below:
Can I get just 2 columns in the bcp?
Starting copy...
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]String data, right truncation
BCP copy in failed -
Parsing Column Value. SQL / Stored Proc/ Function ?
Hi,
I just started writing SQL. Need your valuable input for the following query,
Need to query a table and parse a column to produce a desired output.
like suppose my column value is
#ADFA
/SDFGAS
{ABC}: 123
{BCA}: 456
{DEF}: 789
and i need to get an out put as follows
{ABC} {BCA} {DEF}
123 456 789
so the patterns are defined.
I some how tried and reached through SQL, but there should be better way than this. So posted this question.
I tried using SQL itself (using substr, instr & decode functions in the select statement)... with out using stored proc/ function as i have not created one earlier.. I am just learning the syntax and trying it.
The psuedo code i have planned is
function substring(column_value, search_string)
var start_index NUMBER;
var end_index NUMBER;
var result VARCHAR2;
result = 'N/A';
start_index = instr(column_value, search_string) + 4
if start_index >= 4
end_index = instr(substr(column_value, 0, start_index), CHR(13)-1)
if start_index >= 4 && end_index >=0
result = substr(column_value, start_index, end_index);
return result;
I just wrote it like writing in a programming language. Need to implement this through Stored Proc/ Function. Please let me know your comment on thisOops, I think regular expressions are not available in my current oracle version :-(
I am having Oracle 9i.
Got it.. Yes it is available from 10G onwards.. :-(
Message was edited by:
Thiru.Thiru -
Cannot get Universe column in the sql server ?
Hi,
I able to get some of columns using below query , but I cannot get some of the columns from universe to SQL Server.
If I try through SSIS also the columns are missing which are unable to get using openquery.
If I add "Microsoft ODBC Data Source (ODBC)" for Universe U2 also then some of the columns are missing .
For Example : Unable to get "Description" Column.
How can I check what is the problem ? Please help me on this..
select * FROM OPENQUERY(ulive, 'select Description
FROM TABLENAME WHERE Z_ID=''020324.doc''')
Msg 7321, Level 16, State 2, Line 1
An error occurred while preparing the query for execution against OLE DB provider "MSDASQL" for linked server "ulive".
Thank you..What is Universe U2 server? Is it SQL Server or Oracle or perhaps MySQL?
select Description FROM ULIVE.DBNAME.DBO.TABLENAME WHERE Z_ID='020324.doc'
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence
Maybe you are looking for
-
Can't create a new illustration. Problems occurred while saving the print file.
I can't open a new Illustrator file. It sends me this error: Can't create a new illustration. Problems occurred while saving the print file. ID:-1 I opened a previous document created in CC, but it will not allow me to copy and paste items from one d
-
Hi All Just purchased ARD and i need to know is it possiblt to log on to another mac and take control etc, over the interent. EG. I have a mac at home and i have another mac at the other end of the country, i have put the IP address in of the mac i w
-
PhotoShop Elements 12 Compatability with Premier 11
I installed PhotoShop Elements 12 on a Windows 8.1 Desktop (i7CPU W/16GB RAM) that already had PhotoShop Elements 11 and Premier 11 installed on it. When I try to export a project from Elements 12 to Premier 11, Elements 12 tells me that I must down
-
1520 measure voltage normalized?
I'm using 1520's to replace some old signal conditioning amplifiers in a wind tunnel. Our sensors include pressure transducers and load cells on a force balance. They act like strain gages in that they require an excitation voltage, and produce a sma
-
[Solved] gmrun & Openbox menu can't launch program but bash can.
Hey there. Got myself a bit of a confusing problem. I recently installed the latest of Natron, in /opt/Natron, and added the path to the PATH variable in the .bashrc file, and i can launch it if I'm on bash, but gmrun and the Openbox menu can't loca