Monday, March 12, 2012
Re-using Identity achieved after INSERT query
I'm using an INSERT query to add records to a table with a defined
Identity column.
The query looks like this:
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT SCOPE_IDENTITY();
The return value is Text_ID, and I'm using the it for another insert
query:
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
SELECT SCOPE_IDENTITY();
Is there a way to combine the two queries into a single query ?
Something like this:
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT SCOPE_IDENTITY() = Text_ID;
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
SELECT SCOPE_IDENTITY();
Thanks to all.You can use variable for this.
Declare @.TextID int
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',9,1);
SELECT @.TextID = SCOPE_IDENTITY();
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,@.TextID ,1);
...
MC
"Avital" <avital.chissick@.gmail.com> wrote in message
news:1193566518.353471.43280@.v3g2000hsg.googlegroups.com...
> Hi all,
> I'm using an INSERT query to add records to a table with a defined
> Identity column.
> The query looks like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY();
> The return value is Text_ID, and I'm using the it for another insert
> query:
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Is there a way to combine the two queries into a single query ?
> Something like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY() = Text_ID;
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Thanks to all.
>|||I think you just need to use a variable:
DECLARE @.TextId INT
INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
9,1);
SELECT @.TextId = SCOPE_IDENTITY();
INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,@.Text_ID,1);
SELECT SCOPE_IDENTITY();
Adam Machanic
SQL Server MVP - http://sqlblog.com
Author, "Expert SQL Server 2005 Development"
http://www.apress.com/book/bookDisplay.html?bID=10220
"Avital" <avital.chissick@.gmail.com> wrote in message
news:1193566518.353471.43280@.v3g2000hsg.googlegroups.com...
> Hi all,
> I'm using an INSERT query to add records to a table with a defined
> Identity column.
> The query looks like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY();
> The return value is Text_ID, and I'm using the it for another insert
> query:
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Is there a way to combine the two queries into a single query ?
> Something like this:
> INSERT INTO Table_A (Text,Size,CountOcur) VALUES ('copyright123',
> 9,1);
> SELECT SCOPE_IDENTITY() = Text_ID;
> INSERT INTO Table_B (FileID,TextID,TextLocaton) VALUES (1,Text_ID,1);
> SELECT SCOPE_IDENTITY();
> Thanks to all.
>
Wednesday, March 7, 2012
returning unique data
want to return the name of the first row (first meaning lowest rowid) when
there are more than one row with the same number. Given the table looks
like this:
number name rowid
102 bob 1
102 allen 2
104 carl 3
104 mike 4
I want only bob and carl to be returned.
Can anyone point me in the right direction?
Tx for any help.
Bernie YaegerYou're looking for a correlated subquery.
CREATE TABLE #foo
(
rowid INT IDENTITY(1,1),
[name] VARCHAR(12),
[number] INT
)
SET NOCOUNT ON
INSERT #foo([name], [number]) SELECT 'bob', 102
INSERT #foo([name], [number]) SELECT 'allen', 102
INSERT #foo([name], [number]) SELECT 'carl', 104
INSERT #foo([name], [number]) SELECT 'mike', 104
SELECT [name],[number],rowid
FROM #foo f1
WHERE rowid = (SELECT MIN(rowid)
FROM #foo f2
WHERE f2.[number] = f1.[number])
ORDER BY [number]
DROP TABLE #foo
"Bernie Yaeger" <berniey@.optonline.net> wrote in message
news:eN$erwlkFHA.1384@.TK2MSFTNGP10.phx.gbl...
>I have a table with 3 columns: number, name, rowid (and identity column).
>I want to return the name of the first row (first meaning lowest rowid)
>when there are more than one row with the same number. Given the table
>looks like this:
> number name rowid
> 102 bob 1
> 102 allen 2
> 104 carl 3
> 104 mike 4
> I want only bob and carl to be returned.
> Can anyone point me in the right direction?
> Tx for any help.
> Bernie Yaeger
>|||Bernie
CREATE TABLE #Test
(
[ID] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
number INT NOT NULL,
[name]CHAR(1)NOT NULL,
rowid INT NOT NULL
)
INSERT INTO #Test(number,[name],rowid) VALUES (102,'A',2)
INSERT INTO #Test (number,[name],rowid)VALUES (102,'B',1)
INSERT INTO #Test(number,[name],rowid) VALUES (103,'C',1)
INSERT INTO #Test(number,[name],rowid) VALUES (103,'D',2)
INSERT INTO #Test(number,[name],rowid) VALUES (103,'A',3)
INSERT INTO #Test(number,[name],rowid) VALUES (103,'B',4)
INSERT INTO #Test(number,[name],rowid) VALUES (102,'T',0)
INSERT INTO #Test(number,[name],rowid) VALUES (104,'a',2)
SELECT [name]FROM #Test
WHERE rowid=(SELECT MIN(rowid) FROM #Test T WHERE T.number=#Test.number)
"Bernie Yaeger" <berniey@.optonline.net> wrote in message
news:eN$erwlkFHA.1384@.TK2MSFTNGP10.phx.gbl...
>I have a table with 3 columns: number, name, rowid (and identity column).
>I want to return the name of the first row (first meaning lowest rowid)
>when there are more than one row with the same number. Given the table
>looks like this:
> number name rowid
> 102 bob 1
> 102 allen 2
> 104 carl 3
> 104 mike 4
> I want only bob and carl to be returned.
> Can anyone point me in the right direction?
> Tx for any help.
> Bernie Yaeger
>|||Hi Uri,
Tx for your help Uri.
Bernie
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:eLVoxKmkFHA.3568@.TK2MSFTNGP10.phx.gbl...
> Bernie
> CREATE TABLE #Test
> (
> [ID] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
> number INT NOT NULL,
> [name]CHAR(1)NOT NULL,
> rowid INT NOT NULL
> )
> INSERT INTO #Test(number,[name],rowid) VALUES (102,'A',2)
> INSERT INTO #Test (number,[name],rowid)VALUES (102,'B',1)
> INSERT INTO #Test(number,[name],rowid) VALUES (103,'C',1)
> INSERT INTO #Test(number,[name],rowid) VALUES (103,'D',2)
> INSERT INTO #Test(number,[name],rowid) VALUES (103,'A',3)
> INSERT INTO #Test(number,[name],rowid) VALUES (103,'B',4)
> INSERT INTO #Test(number,[name],rowid) VALUES (102,'T',0)
> INSERT INTO #Test(number,[name],rowid) VALUES (104,'a',2)
>
> SELECT [name]FROM #Test
> WHERE rowid=(SELECT MIN(rowid) FROM #Test T WHERE T.number=#Test.number)
>
>
> "Bernie Yaeger" <berniey@.optonline.net> wrote in message
> news:eN$erwlkFHA.1384@.TK2MSFTNGP10.phx.gbl...
>|||Hi Aaron,
Tx so much for your help.
Bernie
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:ORACDEmkFHA.708@.TK2MSFTNGP10.phx.gbl...
> You're looking for a correlated subquery.
>
> CREATE TABLE #foo
> (
> rowid INT IDENTITY(1,1),
> [name] VARCHAR(12),
> [number] INT
> )
> SET NOCOUNT ON
> INSERT #foo([name], [number]) SELECT 'bob', 102
> INSERT #foo([name], [number]) SELECT 'allen', 102
> INSERT #foo([name], [number]) SELECT 'carl', 104
> INSERT #foo([name], [number]) SELECT 'mike', 104
> SELECT [name],[number],rowid
> FROM #foo f1
> WHERE rowid = (SELECT MIN(rowid)
> FROM #foo f2
> WHERE f2.[number] = f1.[number])
> ORDER BY [number]
> DROP TABLE #foo
>
>
> "Bernie Yaeger" <berniey@.optonline.net> wrote in message
> news:eN$erwlkFHA.1384@.TK2MSFTNGP10.phx.gbl...
>
Returning timestamp from inserted record using @@Identity
i recently found a little error in a stored procedure that was included in a project handed over to me....
the sp was rather simple. it just inserted a record into a table and returned the identity and the timestamp as follows
IF @.@.ERROR>0
BEGIN
SELECT @.int_InterventionID = 0
RETURN @.@.ERROR
END
ELSE
BEGIN
SELECT @.int_InterventionIDReturned = MAX(InterventionID) FROM tblIntervention
SELECT @.ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @.int_InterventionIDReturned
SELECT @.int_InterventionID = @.int_InterventionIDReturned, @.ts_Timestamp = @.ts_TimestampReturned
RETURN 0
END
i figured that it should be using @.@.Identity for the interventionIdentity rather than max(InterventionID)
so i changed to...
IF @.@.ERROR>0
BEGIN
SELECT @.int_InterventionID = 0
RETURN @.@.ERROR
END
ELSE
BEGIN
SELECT @.int_InterventionIDReturned = @.@.IDENTITY
SELECT @.ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @.int_InterventionIDReturned
SELECT @.int_InterventionID = @.int_InterventionIDReturned, @.ts_Timestamp = @.ts_TimestampReturned
RETURN 0
END
it returns the @.int_InterventionIDReturned but the timestamp now comes back as null? why?
how can i ensure that i always get the timestamp of the record it has just inserted
any help greatly appreciated,
Cheers,
Craig
Craig:
Try to use SCOPE_IDENTITY() instead of @.@.identity or Max (InterventionID).
|||nice one, that work perfectly.Dave
Cheers,
Craig
Returning the next identity value before writing a record.
Insert the new row and the related rows in a transaction, or add a "Pending" flag to the table, and have it default to True (meaning it is pending) and then have other parts of the system look for Pending==false rows.|||you can change the data type to uniqueidentifier, that way you'll knowthe id of that row since you'll be passing it a Guid that you create.
|||
In SQL Server GUID is a 16bytes binary data type, run a search for NEWID in the BOL (books online) and another option is DBCC CHECKIDENTITY. Try the link below for DBCC CHECKIDENTITY. Hope this helps.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_dbcc_5lv8.asp
returning the Identity of the auto number column
How to write the Sql Query to return the next generated Identity from the Sql server database.Which version of SQL Server are you using?
If <= 7.0 - have a look at @.@.identity
If 2000 - have a look at SCOPE_IDENTITY
Returning Text + Column
CREATE TABLE [dbo].[Tester] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[TesterText] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Tester] WITH NOCHECK ADD
CONSTRAINT [PK_Tester] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
GO
insert into Tester (TesterText) Values ('AAAA')
insert into Tester (TesterText) Values ('BBBB')
insert into Tester (TesterText) Values ('CCCC')
insert into Tester (TesterText) Values ('DDDD')
Given the above Schema and insert I would like to return a varchar with text
+ the column TesterText, so in this case I would like a varchar with 'Hello
AAAA;Hello BBBB;Hello CCCC;Hello DDDD;'.
I would rather not use cursors.
TIA
JJulie
Why not doing shuch things on the client side
I did not check NULLs and for another world it does not work as well
DECLARE @.v VARCHAR(100)
SET @.v=''
SELECT @.v=@.v+''+TesterText+';'+'Hello' FROM Tester
SELECT REPLACE(LEFT(@.v,LEN(@.v)-6),' ','')+';'
"Julie" <Julie@.discussions.microsoft.com> wrote in message
news:3C344282-FD6C-46DC-B051-1830200B247B@.microsoft.com...
> Dear All
> CREATE TABLE [dbo].[Tester] (
> [ID] [int] IDENTITY (1, 1) NOT NULL ,
> [TesterText] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[Tester] WITH NOCHECK ADD
> CONSTRAINT [PK_Tester] PRIMARY KEY CLUSTERED
> (
> [ID]
> ) ON [PRIMARY]
> GO
> insert into Tester (TesterText) Values ('AAAA')
> insert into Tester (TesterText) Values ('BBBB')
> insert into Tester (TesterText) Values ('CCCC')
> insert into Tester (TesterText) Values ('DDDD')
> Given the above Schema and insert I would like to return a varchar with
text
> + the column TesterText, so in this case I would like a varchar with
'Hello
> AAAA;Hello BBBB;Hello CCCC;Hello DDDD;'.
> I would rather not use cursors.
> TIA
> J
>|||The best place for this kind of non-relational concatenation is on the
client, not in the database. However, see http://www.aspfaq.com/2529 for a
starting point if you really, really, really want to do this in the
database.
On 3/15/05 6:05 AM, in article
3C344282-FD6C-46DC-B051-1830200B247B@.microsoft.com, "Julie"
<Julie@.discussions.microsoft.com> wrote:
> Dear All
> CREATE TABLE [dbo].[Tester] (
> [ID] [int] IDENTITY (1, 1) NOT NULL ,
> [TesterText] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[Tester] WITH NOCHECK ADD
> CONSTRAINT [PK_Tester] PRIMARY KEY CLUSTERED
> (
> [ID]
> ) ON [PRIMARY]
> GO
> insert into Tester (TesterText) Values ('AAAA')
> insert into Tester (TesterText) Values ('BBBB')
> insert into Tester (TesterText) Values ('CCCC')
> insert into Tester (TesterText) Values ('DDDD')
> Given the above Schema and insert I would like to return a varchar with te
xt
> + the column TesterText, so in this case I would like a varchar with 'Hell
o
> AAAA;Hello BBBB;Hello CCCC;Hello DDDD;'.
> I would rather not use cursors.
> TIA
> J
>|||Thanks Guys,
I have given Uri the 'answered' as he was the first :D
Anyway what I'm actually doing is preparing a number of Dynamic SQL
Statments for a nightly batch run (we have the column + table names in a
table) however I couldn't find a way of concatinating them together.
Anyway thanks for that
J
"Julie" wrote:
> Dear All
> CREATE TABLE [dbo].[Tester] (
> [ID] [int] IDENTITY (1, 1) NOT NULL ,
> [TesterText] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[Tester] WITH NOCHECK ADD
> CONSTRAINT [PK_Tester] PRIMARY KEY CLUSTERED
> (
> [ID]
> ) ON [PRIMARY]
> GO
> insert into Tester (TesterText) Values ('AAAA')
> insert into Tester (TesterText) Values ('BBBB')
> insert into Tester (TesterText) Values ('CCCC')
> insert into Tester (TesterText) Values ('DDDD')
> Given the above Schema and insert I would like to return a varchar with te
xt
> + the column TesterText, so in this case I would like a varchar with 'Hell
o
> AAAA;Hello BBBB;Hello CCCC;Hello DDDD;'.
> I would rather not use cursors.
> TIA
> J
>
Saturday, February 25, 2012
Returning Scope_Identity from Stored Procedures
Hi:
I've seen a lot of posts about returning the identity after an insert but for every variation, the return value or output parameter is null. Below is the sp, SQLDataSource and vb code for the return value attempt.
Here is the stored procedure:
ALTER PROCEDUREdbo.sp_InsertPlayer
(
@.UserNamevarchar(64),
@.Emailvarchar(128)
)AS
INSERT INTOtblPlayer ([UserName],)
VALUES(@.UserName, @.Email)
RETURN SCOPE_IDENTITY()
If the sp is executed in the SQL Express that is included in VS 2005, the return value is the last autogenerated PlayerId.
SqlDataSource:
<asp:SqlDataSourceID="SqlDataPlayer"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand ...
InsertCommand="sp_InsertPlayer"
InsertCommandType="StoredProcedure"
>
...
<InsertParameters>
<asp:ParameterName="RETURN_VALUE"Direction="ReturnValue"Type="Int32"/>
<asp:ParameterName="UserName"Type="String"/>
<asp:ParameterName="Email"Type="String"/>
</InsertParameters>
</asp:SqlDataSource>
code behind vb:
SqlDataPlayer.InsertParameters("UserName").DefaultValue = CreateUserWizard1.UserName
SqlDataPlayer.InsertParameters("Email").DefaultValue = CreateUserWizard1.Email
SqlDataPlayer.Insert()
Profile.PlayerId = SqlDataPlayer.InsertParameters("RETURN_VALUE").DefaultValue
The DefaultValue is Nothing.
Thanks for your help again.
arora
What I end up doing is something like this:
...
SELECT ScopeIdentity = SCOPE_IDENTITY()
That was back in the .NET 1.1 days, so I don't know if that would be of use with the SqlDataSource. Does that work?
|||That doeswork (in fact that is my workaround) but just the integer identity value needs to be returned.
Using the SELECT, a result set with one column ScopeIdentity is returned.
I have to use code similar to below to access the identity value:
SqlDataPlayer.SelectParameters("UserName").DefaultValue = CreateUserWizard1.UserName
Dim argsAs DataSourceSelectArguments =New DataSourceSelectArguments()
Dim dvAs Data.DataView
dv = SqlDataPlayer.Select(args)
Session("PlayerId") = dv.Table.Rows(0).Item("PlayerId")
and the sp is:
ALTER PROCEDUREdbo.sp_PlayerIDFromUserName
(
@.UserNamevarchar(64)
)
AS
SELECTPlayerIDFrom[tblPlayer]
WHERE[UserName] = @.UserName
It just seems there has to be an easier way than returning a table for one value.
|||The return value is only available in the SqlDataSource_Inserted event.|||Thanks Motley.
Here's a link with an example.
http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.inserted.aspx
Tuesday, February 21, 2012
returning key value with Insert
Hello,
Use SCOPE_IDENTITY() or @.@.IDENTITY
e.g
SELECT @.@.IDENTITY
HTH
regards
|||
Thanks. Sorry, I still don't understand (fairly new to ASP.net). Code is below. After my 'ExecuteNonQuery' command is performed, I want to know the value of the IdentityColumn (not referenced in code below) that was automatically added. ?? Thanks for your patience.
******************************************************************************************
PublicSharedFunction AddReport(ByVal passRepLayoutAs Report)AsBoolean
Dim dbConnectionAs SqlConnection = QuoteDBConnection()
Dim sAddAsString = "Insert Into Report(QuoteNumber, Driver, ReportType, ReportID, OrderDate, DataFile) " _
& "Values(@.QuoteNumber, @.Driver, @.ReportType, @.ReportID, @.OrderDate, @.DataFile)"
Dim dbCmdAsNew SqlCommand(sAdd, dbConnection)
With passRepLayout
dbCmd.Parameters.Add("@.QuoteNumber", .QuoteNumber)
dbCmd.Parameters.Add("@.Driver", .Driver)
dbCmd.Parameters.Add("@.ReportType", .ReportType)
dbCmd.Parameters.Add("@.ReportID", .ReportID)
dbCmd.Parameters.Add("@.OrderDate", .OrderDate)
dbCmd.Parameters.Add("@.DataFile", .DataFile)
EndWith
dbConnection.Open()
Try
dbCmd.ExecuteNonQuery()
IdentityColumnValue = ?
AddReport =True
Catch exAs Exception
AddReport =False
EndTry
dbConnection.Close()
EndFunction
|||Dim sAddAsString="Insert Into Report(QuoteNumber, Driver, ReportType, ReportID, OrderDate, DataFile) " _
&"Values(@.QuoteNumber, @.Driver, @.ReportType, @.ReportID, @.OrderDate, @.DataFile) SELECT SCOPE_IDENTITY()"
and use ExecuteScalar instead of ExecuteNonQuery.
dim resultidasinteger
resultid= dbCmd.ExecuteScalar()
|||Thank- you very much.Returning identity field
Hi all i'm trying to get the identity field after inserting into db, what am i doing wrong? thanks a lot
my sproc:
CREATE PROCEDURE ng_AddCotacao
(
...
@.Codigo_cotacao int OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO
Negocios_cotacoes
(
...
)
VALUES
(
...
)
SELECT @.Codigo_cotacao=SCOPE_IDENTITY()
SET NOCOUNT OFF
END
GO
class file
public
class Cotacoes{
publicint codigoCotacao;
}
public class CotacaoAtualiza
{
public Cotacoes cotacoes = new Cotacoes();
public CotacaoAtualiza()
{
}
public void AdicionarCotacao(
...
)
{
SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["stringConexao"]);
SqlCommand myCommand = new SqlCommand("ng_AddCotacao", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
...
SqlParameter paramCodigo_cotacao = new SqlParameter("@.Codigo_cotacao", SqlDbType.Int, 4);
paramCodigo_cotacao.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(paramCodigo_cotacao);
...
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader();
while(result.Read())
{
this.cotacoes.codigoCotacao = (int) result["@.Codigo_cotacao"];
}
myConnection.Close();
}
calling into code-behind file:
CotacaoAtualiza ca =
new CotacaoAtualiza();Cotacoes cotacoes = ca.cotacoes;
Response.Redirect("Cotacao_confirma.aspx?cotacao=" + cotacoes.codigoCotacao);
You don't get the result in the resultset but rather in the parameter - ex:
System.Data.SqlClient.
SqlCommand Cmd =new System.Data.SqlClient.SqlCommand("AddSomething", oConn);Cmd.CommandType =
CommandType.StoredProcedure;System.Data.SqlClient.
SqlParameter oParam = Cmd.Parameters.AddWithValue("@.zonename", sName);oParam = Cmd.Parameters.AddWithValue(
"@.desc", sDesc);oParam = Cmd.Parameters.AddWithValue(
"@.TheNewId", 0);oParam.Direction =
ParameterDirection.Output;Cmd.ExecuteNonQuery();
oConn.Close();
int nTheNewId =Convert.ToInt32(Cmd.Parameters["@.TheNewId"].Value);Returning Identity column in SQL 7
Anyone remember how they did this ?@.@.Identity