can somebody explain me, why the IDENT_CURRENT from an empty table is 1?
After insert of the first record it is still 1 (assuming that start value
is 1) which is okay. But if i check the IDENT_CURRENT from a newly created
table the result should be NULL, or not?
Hi I am trying to get the last ID value of a table. The following code worked when a SQLConnection object was used, how do I achieve the same result using an SQLDataSource? this.sqlSelectCmd2 = new System.Data.SqlClient.SqlCommand("SELECT IDENT_CURRENT('Assets')",sqlConnection1); sqlConnection1.Open(); int nID = Convert.ToInt32( this.sqlSelectCmd2.ExecuteScalar() ) ; nID++; dc.FocusedRow["ID"] = nID.ToString(); Cheers Pen
I have a SSIS package that imports data into a staging table from an excel sheet (This works fine). From the staging tabler i want it to insert the values into my members table, take that unique indentityID that gets created and insert the other values into other tables for that member that was just created.
In the staging table, i have all the values for a single member. But the structure of the database needs all the values inserted into seperate tables. There is no conditions ID in my members table, so the member first has to be created and from there i need to use the newly created member's MemberID and insert the conditions into a seperate table using the MemberID
I have created some sample data that can be used. I think i have an idea of how to do it, but i'm not totally sure if it will work that way, i have however included it in the sample data.
Code Snippet DECLARE @ImportedStagingData TABLE ( ID INT IDENTITY(1,1), Name VARCHAR(50), Surname VARCHAR(50), Email VARCHAR(50), [Chronic Heart Failure] INT, [Colon Cancer] INT ) INSERT INTO @ImportedStagingData VALUES ('Carel', 'Greaves', 'CarelG@Email.com', 1,0) INSERT INTO @ImportedStagingData VALUES ('Jamie', 'Jameson', 'JamieJ@Email.com', 1,1) INSERT INTO @ImportedStagingData VALUES ('Sarah', 'Bolls', 'SarahB@Email.com', 0,1) INSERT INTO @ImportedStagingData VALUES ('Bells', 'Scotch', 'BellsS@Email.com', 1,1) INSERT INTO @ImportedStagingData VALUES ('Stroh', 'Rum', 'StrohR@Email.com', 0,0) DECLARE @Conditions TABLE ( ID INT IDENTITY(1,1), Condition VARCHAR(50) ) INSERT INTO @Conditions VALUES ('Chronic Heart Failure') INSERT INTO @Conditions VALUES ('Colon Cancer') DECLARE @Members TABLE ( MemberID INT IDENTITY(1,1), Name VARCHAR(50), Surname VARCHAR(50), Email VARCHAR(50) ) DECLARE @memConditions TABLE ( MemberID INT, ConditionID INT ) SELECT * FROM @ImportedStagingData SELECT * FROM @Conditions SELECT * FROM @Members SELECT * FROM @memConditions /* --- This is the part that i am battling with --- DECLARE @CurrentValue INT DECLARE @numValues INT SET @numValues = (SELECT COUNT(ID) FROM @ImportedStagingData) WHILE @numValues <> 0 BEGIN INSERT INTO @Members SELECT Name, surname, email FROM @ImportedStagingData GO SET @CurrentValue = (SELECT IDENT_CURRENT('@ImportedStagingData')) INSERT INTO @memConditions (MemberID), (ConditionID) VALUES (@CurrentValue, --ConditionValue from @ImportedStagingData, all the values that have a 1)
Hello, I have tried developped a stored proc that is using the ident_current('tablename') function to get the last Identity ID.
It was working fine. I drop and recreate the table (which reset the ID) and found that the ident_current said that the last Identity Id used was 1. The problem was that the table was empty. I insert a record and try it again. It said again that the last Identity ID was 1. After the insertion if the first record, everything is fine...
I would like to know if you know a way get 0 when the table is empty and 1 when there is only one identity id that have been used.
Thank
Felix Pageau fpageau@str.ca
You can test the functionnality with the following code:
create table identCurrentBugExeample(IDnumber int IDENTITY(1,1), aChar char(1)) Declare @count as int set @count = (select count(IDnumber) from identCurrentBugExeample)
--Print the number of record in the table print @count
--Supposed to print 0 because there isn't any identity values that has been used print ident_current('identCurrentBugExeample') insert identCurrentBugExeample(aChar) values('a')
--Print 1 because the last identity used is 1 print ident_current('identCurrentBugExeample') insert identCurrentBugExeample(aChar) values('a')
--Print 2 because the last identity used is 2 print ident_current('identCurrentBugExeample') drop table identCurrentBugExeample
All, Using access 2003 frontend and sql server 2008 backend. I have an append query to insert 80000 from one table to an empty table. I get an error:
"Microsoft Office Access set 0 field(s) to Null due to a type conversion failure, and didn't add 36000 record(s) to the table due to key violations, 0 record(s) due to lock violations, and 0 record(s) due to validation rule violations."
I know this error normally comes if there are dups in a field that doesnt allow.
I found a strange problem with IDENT_CURRENT returning NULL value in all my SP's in which it is used.Following are the general reasons why it returns NULL :1. Its executed against the Empty table.2. Table does not Identity column.But i could check that above two point were not a prolblem for me. The problem was the database user has only db_executor permissions. If it is set to db_owner all my insert SP's work's as it should. But it fails otherwise.Can anybody throw some lights here ?
I have Server1(MSSQL7) & Server2(MSSQL 2000) are linked. For trigger purpose I need to access latest identity value from Server2.mydatabase.mytable in Server1 so I have statement as follows
Hi thereI have small problem with IDENT_CURRENT...We have a table where PK is generated automatically.What I want is to get that value and insert it to another,corresponding table.So here is what I am doing...BEGIN TRANInsert Into table() --> PK is created.SELECT IDENT_CURRENT('Table_Name') AS lastValueCOMMIT TRanIT works fine, but there is a possibility to insert another record byanother user before I get my IDENT_CURRENT.For instance:BEGIN TRANInsert Into table() --> PK is created.---->somebody else inserts another record into same table.SELECT IDENT_CURRENT('Table_Name') AS lastValue---->this is not the value that I generated....COMMIT TRan
I have a table that uses an identity column. I have a second column that will contain the current identity value or, when the original row is replaced, the identity value of the replacing row.
USE [test] GO /****** Object: Table [dbo].[test1] Script Date: 04/10/2008 14:04:22 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[test1]( [col1] [int] IDENTITY(1,1) NOT NULL, [col2] [int] NOT NULL, [col3] [varchar](max) NOT NULL, [ts] [timestamp] NOT NULL, CONSTRAINT [PK_test1] PRIMARY KEY CLUSTERED ( [col1] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF
My question is on the insert is it safe to use the following statement to insert the new identity value to the second column?
INSERT INTO test1 (col2, col3) VALUES (IDENT_CURRENT('test1'), 'test')
BOL says (or has had added ) on the subject of IDENT_CURRENT
Exceptions
Returns NULL on error or if a caller does not have permission to view the object.
In SQL Server 2005, a user can only view the metadata of securables that the user owns or on which the user has been granted permission. This means that metadata-emitting, built-in functions such as IDENT_CURRENT may return NULL if the user does not have any permission on the object.
However am finding that SCOPE_IDENTITY does continue to function for a user who has not been granted meta data permisisons or directly (select) on the underlying table.
can somebody explain why they are different behaviours. I need to be able to capture the ID of a row just inserted (under the insert rights of my application role) I'm glad SCOPE_IDENTITY works but am nervous am working in an area of undefined behaviour ! after all its also a metadata-emitting, built-in function
My application role is the owner of the schema and the storedprocedure which trys to use IDENT_CURRENT but it consistently returns me a null when logged in as a user without admin priveleges
Hello, The following statement behave different between SQL2000 and SQL2005. On our database we have some insert statements like that, and as we test our DB for SQL2005, we have found this difference. Can anyone tell me why?
hi to all who is the best use among IDENT_CURRENT and @@IDENTITY and SCOPE_IDENTITY when i wnat to get last inserted id from a table. and also give the reason why because i am little bit confuse for useing these.. thanks in advance. arvind
I am creating three tables in a DataSet using three stored procedures and I need a way to know that either the tables have at least one row or preferably which if any has no rows. How can I do that? using three SP's, one for each table:SqlCommand cmd = new SqlCommand("CompanyCheck", con);SqlCommand cmd2 = new SqlCommand("ContractorVerify", con);SqlCommand cmd3 = new SqlCommand("StoreLocation", con); cmd.CommandType = CommandType.StoredProcedure; cmd2.CommandType = CommandType.StoredProcedure; cmd3.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CompanyID", CompanyID); cmd2.Parameters.AddWithValue("@CompanyID", CompanyID); cmd3.Parameters.AddWithValue("@CompanyID", CompanyID); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); try { da.Fill(ds, "CompanyInfo"); da.SelectCommand = cmd2; da.Fill(ds, "ContractorInfo"); da.SelectCommand = cmd3; da.Fill(ds, "StoreInfo"); } catch { throw new ApplicationException("Data error"); } finally { con.Close(); } Thank you
I have a particular production database that on a few recent occasions has suddenly had one of it's tables empty of content. Now there are no jobs or triggers in place neither is any stored procedures that could perform a delete or alter table operation in place. The permissions have been set not to allow this either. The datatype is text only. What is intriguing is the QA server has an exact mirror and this dosen't happen. Has anyone come across this sort of phenomenon?
I can use the Design Table option in every database and any user table on my server except for two databases which were transfered from a SQL 6.0 server.
I can't even use Design Table to create a new table in these databases. I get the Design form up and it allows me to add columns, but when I try to save the changes I get the following error message:
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near 'full'. [Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near 'full'.
One thing I have noticed is under Users for the database, all my users come up as 'via group membership' for the Database Access column for the database I am having problems with. All other databases the users come up as 'Permit' for the Database Access column. I assume this has to do with security. But I have tried everything to change this. I can not get a user to come up as 'Permit' under these two converted databases.
I'm running SQL 2000 (SP3) on top of Windows NT 4.0 (SP6).
I have a couple of processes that look at the sysperfinfo table every day to collect some performance/metric type information. It works for all my other servers (mostly SQL 2K/Win2K) except for this one.
Why is the table on this one server empty?
I do have one other SQL 2K/Win NT server. The sysperfinfo table on that one is fine.
the only other clue/difference is that the server which has the empty table is a named instance install of SQL 2K.
In Access I have a macro that, each night, takes a table with aprimary key defined in it, and deletes all the rows. Then itimports/appends records from a fixed width text file. In this way,since the table is not deleted and recreated, the primary key is keptintact.What would be the equivalent SQL method for doing this in an automatedway? I've tried letting DTS import the table from Access, but theprimary key is lost. Is there some way to "empty" a table instead ofdropping it, and then append new records so that the table will end uphaving the primary key I want it to have?Thanks.Larry- - - - - - - - - - - - - - - - - -"Forget it, Jake. It's Chinatown."
When i try to insert new rows using SSIS into an emty table in my database, SSIS freezes. The same happens when i use a lookup on an empty table.
The only solution i have found is to manualy insert a row and remove it afterwards. When i have done this SSIS works without a glitch.
I start off by taking a script of a existing database and applying this script on a new database. So that i create an empty duplicate of my current database.
Any ideas why SSIS freezes? Do i have to initialize something first in my database? It is really annoying that i have to insert a row and delete a row into every table i want to use.
I'm using the Business Intelligence Studio for designing reports in VS2005 with SQL-Server 2005 Standard used on a TFS server.
On my report I have several tables each related to a previously defined dataset. Now, if a dataset returns no data, I would expect, that the table shows the header but no rows. This is true, if the table is located on the first page of the report and used directly in the preview tab of a report project. If such a table is located on following pages, I get an rsInternalError when switching to the second page. Trying to export the report, e.g. pdf, directly results in this error. When trying to view the report on the report server, the error appears also at once. If, in Visual Studio, clicking on the button "page layout" everything is fine: empty tables are shown correctly.
How can I avoid this error in my reports? I would like to publish my report (no fancy stuff, just simple text data), possibly containing empty tables, on the server that all team members can view it - without the error...
I am trying to work with a developer test a code change in their application. The db basically has a workload table and as it finishes processing each row in the table, it gets deleted from the table. I want to monitor when the db becomes empty/no rows in it to test how much the code changes have worked, how long does it take to process all rows in the table. Any quick way to do it at the db level instead of having to put something in the code just for this testing.
I was wondering what the best way was to deal with subscriptions breaking due to an empty table. I have subscriptions that people have scheduled to go out daily, but on certain days the table may be empty, in this case the subscription doesn't read the parameters for the report and then the subscription breaks.
My original solution involved creating a #temp table with the same columns as the original table and inserting one row into it which I'd union with the original table, this row in the temp table had all its values set to 0. The solution worked when I ran it in SQL Server Management Studio but it seems SRS doesn't like the INSERT INTO statement, which is the error I get, but I've read on these forums that it doesn't like #temp tables either. I proceeded to use a stored procedure with all the code in it, but I might have trouble filtering on multi value parameters, because at times these parameter lists get real big, plus I have to do this for multiple reports and don't want to get into creating stored procedures for each report.
Following is what the code I used look something like that executes and does the job in Management Studio but not SRS. I'm mainly just looking for the easiest and cleanest way to do this, since it'll have to be done across multiple reports, so disregard the code if there's an easier way to do it. Thanks in advance.
create table #dummytable ( name varchar(35), country varchar(35), idnumber (int) ) GO
insert into #dummytable (name),values('0');
select name, country, idnumber from originaltable where name in (@name)
union select name = 0, country = 0, idnumber = 0 from #dummytable
How do I go about iterating through every table in my database and empty each table so they contain no data? I don't want to drop the tables and re-create them either.
Hello,I'm a beginner in SQL and I have been searching through the SQL Cookbook and Google but I can't seem to find an example of what I want to do. I want to create a report that will return names and emails using two of my tables. I want to use the email in my primary table in the select but if it is null or empty I want to replace it with an email from my secondary table. Below is what I would like to do but I got a syntax error with it in SQL Server 2000. SELECT MemberID As ID, MemberFirstName As FirstName, MemberLastName As LastName, (IF MemberEmail = '' THEN SELECT TOP 1 OtherEmail FROM OtherTable WHERE OtherID = MemberID) As EmailFROM PrimaryTableThanks for your time.Jason
I have a column within a table which is already truncated/deleted all records within (Microsoft SQL 2008). I have to now populate the column with sequential numbers up to 50,000 records arbitrary numbers (doesn't mater) up to 7 characters.
what SQL statement I need to write that will automatically polulate the newly empty table with A000001,A0000002,A0000003, or any form for that matter etc so that I can sort number the records within the table.
I have approximately 50000 records which I need to sequentially entered and I really dont want to number the column manually via hand editing.
Hi, is there a way I can check if a table is empty and contains norows?I have a Table1 which being dynamic can sometimes end up with nowcolumns what so ever. I'm using Table1 in one of my views along with 2other tables and I would like put a condition at the...something likeAND Table1 IS NOTEMPTYIs there a way to do this in MS SQL?Many thanksYas
I've built a simple VS2005 ASP.Net web app that uses Crystal Reports for generating assorted reports. More specifically, when a report is called it executes the correct SQL Server Stored Procedure and returns a Data Table populated with with appropriate data. In my testing, everything seemed to be working fine.But I just did a test where I pressed the "Submit" button on two different client browsers at almost the same time. Without fail, one browser returns the report as it should but the other one returns an empty report; all of the Crystal Reports template info is there but the report is just empty of data. Considering that each browser is running in its own session, I'm confused about why this is happening.One thing: I did login as the same user in both cases. Might this be causing the problem?Robert W.Vancouver, BC