Trigger Scope Table

May 15, 2008

Hi,
A need a trigger to scope my data modifications but this code return EventData a NULL. Can someone help me with this?
Thanks




Code Snippet


CREATE TABLE [dbo].[_Log](

[EventID] [int] IDENTITY(1,1) NOT NULL,
[EventData] [xml] NULL,

PRIMARY KEY CLUSTERED
(
[EventID] ASC
) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

---------

CREATE TRIGGER [dbo].[TRG_Clients]
ON [dbo].[Clients]
FOR DELETE,INSERT,UPDATE
AS
INSERT INTO [dbo].[_Log](EventData)
SELECT EVENTDATA()

View 9 Replies


ADVERTISEMENT

Variable Scope And Connection Manger Scope

Mar 13, 2008



I have taken three dtsx files and re written them into one each in its own container. I use the XML Task task alot which the File connection is set by a variable and the variable value is evaluated by expression (the expression makes up the path/filename from other variable values). All the variables that make up the connection are at the container scope. The package will not run now because it is saying that the source (created by variables) for the file connection do not exist.

It seems the answer is that file connections exist at the package level therefore the variable has to be at the package level. This seems to be alot of variables i now have to move to package level to generate the XML source connection. Which in essence makes it confusing as to which variables operate in which container.

My question is can we easily move variable scope (Not ideal as we have alot of variables at package level) Or Can we do the same for connection managers as we do for variables and have them only used in a scope? (this will be ideal as some connections only need to be at a container scope)

View 1 Replies View Related

Transact SQL :: Temp Table Scope On Error

Oct 12, 2015

In my sp I'm have an Insert statement. In the event that after the insert @@rowcount = 0 I'm throwing an error with RAISEERROR.

This is fine, however, in my CATCH block I'm referencing a local temp table but getting an error that it no longer exists.

My question is, does throwing an error drop any #temp tables? I thought they were in scope for the session?

View 4 Replies View Related

What Is The Scope Of A Table Variable Defined In A Dataset?

Dec 14, 2007

if a dataset doesnt use a stored proc to define a table variable, what is the scope of that table variable? Does the name need to be unique from such variables defined by other datasets?

View 4 Replies View Related

Transact SQL :: Table Lock Time Scope

May 8, 2015

I have a query which is part of bigger transaction:

;WITH CTE(
SELECT id, q,
totalQ=SUM(q) OVER (ORDER BY id ROWS UNBOUNDED PRECEDING)
FROM dbo.myTable WITH (UPDLOCK, ROWLOCK)
), CTE1 AS(
SELECT id, q_take=CASE WHEN c.Total<@qRequired THEN c.q ELSE
@qRequired-c.Total+c.q END FROM CTE
WHERE (CASE WHEN c.Total<@qRequired THEN c.q ELSE
@qRequired-c.Total+c.q END)>0
)
UPDATE t set q-=c1.q_take FROM dbo.myTable t INNER JOIN CTE1 c1 ON t.id=c1.id

Because CTE query is executed separately of update query I must put UPDLOCK hint, otherwise myTable could be changed while my query executes by some other user.(I have snapshot row committed transaction).

The problem is that my hint will hold lock on rows of myTable until the end of outer transaction(the bigger one).

But I need lock only for the time of this small query execution. What would be the best way to achieve that?

View 8 Replies View Related

Temp Table Scope In Nested Stored Procedures

Jun 8, 2001

We are migrating a SQL 6.5 application with 1900 stored procedures that use 100's of temp tables to SQL 2000.

A problem we have encountered was that we started out getting an "invalid column" errors on certain procedures. Investigation determined that the error was being generated in a nested procedure. The table that caused the error ended up being a temp table that was created using "select into". The following select statement from that temp table gave the invalid column error.

First thinking it was the "Select Into" we then discovered that the outer most procedure had created a temp table of the same name prior to executing the lower level procedure. After the select into, the next statement was a SELECT that went against what it thought was the inner temp table. However, it grabbed the outermost temp table and then couldn't find the appropriate columns and generated the error.

The solution, of course, was to rename the inner most temp table. We also remove the "select into" in the procedure by explicitly creating the temp table.

We tried creating some test procedures to attempt to reproduce this scenario without complete success.

Our test created 3 procedures (sp1 calling sp2 calling sp3) to mimic the current scenario. Sp1 created a temp table and executed sp2, which executed sp3. Sp3 created another temp table using the same name as the one created in sp1.

If we create all three procedures at the same time, it doesn't matter if we change the order in which they are created or whether we create the inner temp table explicitly or with a "select into", SQL Query Analyzer won't let us create the procedure because it finds that the temp table has been declared twice. If we create the procedures separately however, they compile and allow sp3 to create a temp table by the same name as sp1. After creating the procedures independently, they runs properly in all cases with everything in proper scope and no problems.

Admittedly, this is bad coding to start with, but what is happening with the scope of the temp tables within the stored procedures?

Thanks,
Glen Smith

View 1 Replies View Related

SQL Server 2012 :: Exec Producing Table Out Of Scope

Dec 17, 2013

I am generating some dynamic sql which I would like to run and return the data from, however when I run EXEC(@TEMP_TABLE_STRING) it cannot return the table I think because it is out of scope.

Is there a way around this.

declare@Tablename VARCHAR(150) = 'TEMP_LOCATIONS'
declare@FilterClause VARCHAR(512)=NULL
declare@Classes VARCHAR(100)=NULL
declare@IsExcel BIT = 1
DECLARE @SQL Nvarchar(MAX) = ''
SET NOCOUNT ON;

[Code] ....

View 4 Replies View Related

Trigger Doesn't Log Into The Audit Table If The Column Of Table Has Trigger On Is Null

Jan 23, 2008



Hi,

I have a trigger set on TABLE1 so that any update to this column should set off trigger to write to the AUDIT log table, it works fine otherwise but not the very first time when table1 has null in the column. if i comment out

and i.req_fname <> d.req_fname from the where clause then it works fine the first time too. Seems like null value of the column is messing things up

Any thoughts?


Here is my t-sql


Insert into dbo.AUDIT (audit_req, audit_new_value, audit_field, audit_user)

select i.req_guid, i.req_fname, 'req_fname', IsNull(i.req_last_update_user,@default_user) as username from inserted i, deleted d

where i.req_guid = d.req_guid

and i.req_fname <> d.req_fname



Thanks,
leo

View 7 Replies View Related

SQL Server 2008 :: Techniques For Ensuring Isolated Temp Table Scope?

Jul 28, 2015

what are some common techniques for ensuring an isolated temp table scope? For example, if 2 different sprocs happen to crud a temp table with the same name? I'm guessing that big SQL shops establish a standard for this early on to avoid conflicts between sprocs.

View 3 Replies View Related

CLR-Based Trigger? Recursive Trigger? Common Table Expression?

Nov 14, 2006

Hey,

I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.

A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.

A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.

Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.

If you need the design or create script (table layout), please let me know.

Thanks.

View 4 Replies View Related

Trouble With Update Trigger Modifying Table Which Fired Trigger

Jul 20, 2005

Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'

View 1 Replies View Related

Generic Audit Trigger CLR C#(Works When The Trigger Is Attached To Any Table)

Dec 5, 2006

This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.

The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]

public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);

switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}


//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}

The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.

Comments and Suggestion will be much appreciated.

View 16 Replies View Related

Trigger - Require Help For Updating A Trigger Following An INSERT On Another Table

Oct 30, 2007

Table 1





First_Name

Middle_Name

Surname


John

Ian

Lennon


Mike

Buffalo

Tyson


Tom

Finney

Jones

Table 2




ID

F

M

S

DOB


1

Athony

Harold

Wilson

24/4/67


2

Margaret

Betty

Thathcer

1/1/1808


3

John

Ian

Lennon

2/2/1979


4

Mike

Buffalo

Tyson

3/4/04


5

Tom

Finney

Jones

1/1/2000


I want to be able to create a trigger that updates table 2 when a row is inserted into table 1. However Im not sure how to increment the ID in table 2 or to update only the row that has been inserted.

View 17 Replies View Related

Trigger - Require Help For Updating A Trigger Following An INSERT On Another Table

Feb 5, 2008

A





ID

Name


1

Joe


2

Fred


3

Ian


4

Bill


B





ID


1


4

I want to be able to create a trigger so that when a row is inserted into table A by a specific user then the ID will appear in table B. Is it possible to find out the login id of the user inserting a row?

I believe the trigger should look something like this:

create trigger test_trigger
on a
for insert
as
insert into b(ID)

select i.id
from inserted i
where
--specific USER

View 9 Replies View Related

Trigger On Table LeaveRegister And Inserting Rows In Audit Table

Oct 22, 2012

I write a insert trigger on my table LeaveRegister(1000 rows) and inserting rows in audit table, but when i inserting a row in LeaveRegister table. In audit table 1000 + 1 rows are inserting every time.

View 6 Replies View Related

Update One Table When Records Inserted In Another Table - Variables In Trigger

May 19, 2014

I am trying to update one table when records are inserted in another table.

I have added the following trigger to the table “ProdTr” and every time a record is added I want to update the field “Qty3” in the table “ActInf” with a value from the inserted record.

My problem appears to be that I am unable to fill the variables with values, and I cannot understand why it isn’t working, my code is:

ALTER trigger [dbo].[antall_liter] on [dbo].[ProdTr]
for insert
as
begin
declare @liter as decimal(28,6)

[Code] ....

View 4 Replies View Related

Is Having A Trigger That Inserts A Row In Table 'A', When A Row In Same Table Is Inserted By ADo.Net Code?

Oct 13, 2006

I want to insert a row for a Global user  in Table 'A' whenever ADO.Net code inserts a Local user row into same table. I recommended using a trigger to implement this functionality, but the DBA was against it, saying that stored proecedures should be used, since triggers are unreliable and slow down the system by placing unecessary locks on the table. Is this true OR the DBA is saying something wrong? My thinking is that Microsoft will never include triggers if they are unreliable and the DBA is just wanting to offload the extra DBA task of triggers to the programmer so that a stored procedure is getting called, so he has less headache on his hands.Thanks

View 2 Replies View Related

Trigger For Updating Value On One Table When That Value Is Updated On Base Table

Jul 30, 2015

If the id1 will change in table1 it should also change the corresponding id1 field in table2 it does not do anything.

CREATE TRIGGER [dbo].[IDCHANGE]
ON [dbo].[table1]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from

[Code] .....

View 1 Replies View Related

Trigger- Dump 'inserted' Table To Temp Table

Jul 11, 2006

I want to pass the 'inserted' table from a trigger into an SP, I think I need to do this by dumping inserted table into a temporary table and passing the temp table. However, I need to do this for many tables, and don't want to list all the column names for each table/trigger (maintenance nightmare).

Can I dump the 'inserted' table to a temp table WITHOUT specifying the column names?

View 16 Replies View Related

Scope Identity Again...

Mar 6, 2007

I have been using tis page as a reference http://forums.asp.net/thread/1511323.aspxbut i cant seem to get this to work. The above page suggests using Dim newId As Object = e.Command.Parameters("@RETURN_VALUE").Value to get the value but when i do that i get an error that Command is not a member of system.web.ui.webcontrols.formViewInsertedEventArgs Can anyone help?ThanksMatt 

View 1 Replies View Related

Transaction Scope

Sep 27, 2007

HelloI am trying to run a program to check for transaction scopeI have written the following code.But it seems I need to add a namespace or referenceWhat namespace am I supposed to addthanksusing (TransactionScope scope = new TransactionScope(TransactionScope.Required, options)){SqlConnection MyCon = new SqlConnection("server=hemalatha\sqlexpress;integrated security=sspi;database=demo");MyCon.Open();SqlCommand Mycmd=new SqlCommand("insert into t1 values 574,'scope','10/10/2007',3,3,3");Mycmd.ExecuteNonQuery();SqlConnection MyCon1 = new SqlConnection("server=hemalatha\sqlexpress;integrated security=sspi;database=persons");MyCon1.Open();SqlCommand Mycmd1 = new SqlCommand("insert into persons values 'scope',123,123,12,'scope'");Mycmd1.ExecuteNonQuery();}

View 2 Replies View Related

Scope Identity

Apr 19, 2008

Hi folks
I'm using a function to create a record on a database, and then I want to return the ID of that record to passinto another function. I believe its scope identity that does this, but I'm not sure how to do it.   public static void putrecordin(string record)    {        SqlCommand cmd = new SqlCommand("insert Table (record) values (@record; scope identity)"        conn.Open();        cmd.Parameters.Add(new SqlParameter("@record", record));        cmd.ExecuteNonQuery();        conn.Close();         another(new-record-ID, anothervalue);     }     public static void another(string new-record-ID)    {do stuff
    }
so you'll see I have a function called putrecordin, and at the end of the sql statment I want to return the id of the new record and pass it into another function called another.
Anyone know how to do this?
 Thanks!

View 6 Replies View Related

Scope Of @@datefirst

Oct 7, 2002

I have created a proc that uses @@datefirst to have the weekending on Friday and starting on Saturday.

If I execute the proc from w/in a cursor, a nested cursor, will I have to constantly check and confirm the @@datefirst value?

TIA

JeffP....

View 1 Replies View Related

Question About Scope

Jun 6, 2007

In the following Query, is Table1.Column3 updated in the subquery for each row in Table1, or does it take the first value, or is it NULL, or is it ____?


Select Column1, Column2 from Table1 where Column1 IN
(Select Col1 from Table2 where Col2 > Table1.Column3
Group by Col1 Having count(Col1) > 1) and Table1.Column3 < Column4

View 6 Replies View Related

XML And Scope Identity

Nov 26, 2007

OK, So I'm Getting some XML Like this


<PifToMepData Mode="3">
<MEP MEPName="Test Combining PIFs" MEPType="Close" PIFRecId="12" IsPrimaryPIF="1"><AssignedTo>X000525</AssignedTo></MEP>
<MEP MEPName="Test Combining PIFs" MEPType="Close" PIFRecId="13" IsPrimaryPIF="0"><AssignedTo>X000525</AssignedTo></MEP>
</PifToMepData>


I then use


INSERT INTO #myTemp99 (
Mode
, MEPName
, MEPType
, PIFRecId
, IsPrimaryPIF
, AssignedTo)
SELECT *
FROM OPENXML (@idoc, './/AssignedTo',3)
WITH(
Mode varchar(20) '../../@Mode'
,MEPName varchar(2000) '../@MEPName'
,MEPType varchar(500) '../@MEPType'
,PIFRecId int '../@PIFRecId'
,IsPrimaryPIF varchar(20) '../@IsPrimaryPIF'
,AssignedTo varchar(20) '.'
)


To Parse it out. This then has to be inserted into another table with an identity column (damn Identity column), and I need to grab the generated id for each row, because then there are other children tables that need to be populated.

Question: Is there any set way to grab multiple generated id's?
Or do I need to loop or use a cursor?

Is the 1% of the time that they are needed?

Any ideas?
Here's the temp table DDL


CREATE TABLE #myTemp99 (
Mode varchar(20)
, MEPName varchar(2000)
, MEPType varchar(500)
, PIFRecId int
, IsPrimaryPIF varchar(20)
, AssignedTo varchar(20))


And the document prep
DECALRE @idoc varchar(8000)
--Just assign the sampel data
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

EXEC sp_xml_removedocument @idoc

Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam

View 8 Replies View Related

Scope Of Variable

Dec 4, 2007

Hi,
Is there any way to change the scope of a user defined variable?

View 3 Replies View Related

Scope Of Variable

Dec 4, 2007

Hi,
how to change the a scope of a user defined variable?

View 2 Replies View Related

Index= &<th Scope=col&> ?

Jul 23, 2005

Is an index in a database the equivalent for a <TH scope="col"> in a columnof atable in the html code?--Luigi ( un italiano che vive in Svezia)https://www.scaiecat-spa-gigi.com/s...kor-italien.php

View 3 Replies View Related

Keyword Nothing As The Scope.....

Mar 26, 2007

I've been trying to figure out the usage of "Nothing" as the scope parameter, and the more I try, the more I can confused.

It says on the RDL spec:

"For expressions inside data regions:

.......

Specifying the keyword Nothing as the scope is equivalent to specifying the
outermost data region containing the report item in which the aggregate is used."

It seems that what's it saying is that if I have an expression in a table as
= last(somefield, "the name of the table")
is the same as
= last(somefield,Nothing)
But, apparently it;s not. (I tried last, first,sum, count,CountRows, min, max...........)
it doesn't matter where I put "=last(somefield,Nothing)" in the table (i tried table header,footer, detail, and table group header, footer), none of them worked.
and I tried it everywhere in matrix, in charts.
It's just not working.
It always complains about the invalid scope not being the containing data region, containing grouping or dataset name.

However, the only way I get the "Nothing" as the scope to work is in a RunningValue function, not in any other
aggregate funcitons.

Anyone help me with this, please... I need a complete definition on the usage of Nothing as scope.

View 11 Replies View Related

Variable Scope

Sep 7, 2006

Hello again,

Variable scope of package variables should be in a dropdown. I want to copy (20+) variables from one sequence container to another. Do I have to retype all the names, types and initial values because I made the mistake not to place them one level higher?

Greets,
Tom

View 2 Replies View Related

Increase Scope Of CTE?

Jan 10, 2008



I am really starting to like CTEs. My only qualm is that you can only use them within the first statement after you declare them. I wish they would remain active for the duration of the sql batch just like everything else (variables,local temp tables, ect). Is there any trick so that you can use them multiple times? Maybe define them as a string and do dynamic sql or something like that? Hopefully (i have not researched the new version of sql server) in SQL Server 2008 the scope has increase. Anyways any help would be appreciated.

thanks,
Ncage

View 19 Replies View Related

SCOPE IDENTITY Syntax

Jan 28, 2007

Hi,
I've been trying to insert data in a Sql server (.mdf) db and use SCOPE IDENTITY to be able to insert an id in both the parent and the child tables. However, I don't know how to write one of the lines correctly:
Dim MyConn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
Dim MySQL As String = "INSERT INTO Document (fid, serie, vnr, datum, vtext, sign) " & _
"Values (@fid, @serie, @vnr, @datum, @vtext, @sign) Select @verid=SCOPE_IDENTITY()"
Dim Cmd As New SqlCommand(MySQL, MyConn)
With Cmd.Parameters
.Add(New SqlParameter("@fid", fid))
.Add(New SqlParameter("@serie", SerieDropDownList.SelectedValue))
.Add(New SqlParameter("@vnr", vnr))
.Add(New SqlParameter("@datum", datumet))
.Add(New SqlParameter("@vtext", VtextTextBox.Text))
.Add(New SqlParameter("@sign", sign))
.Add(New SqlParameter("@verid", SqlDbType.Int)) 'HERE IS THE LINE THAT SHOULD BE CHANGED (OR SO I THINK)
End With
MyConn.Open()
Cmd.ExecuteNonQuery()
Dim p As SqlParameter = Cmd.Parameters.Add("@verid", SqlDbType.Int)
p.Direction = ParameterDirection.Output
Dim verid = Cmd.Parameters("@verid").Value.ToString
For Each row As GridViewRow In StampelGridView.Rows
Dim kpnr As String = row.Cells(0).Text
Dim kst As String = row.Cells(1).Text
If kst = "&nbsp;" Then kst = ""
Dim projekt As String = row.Cells(2).Text
If projekt = "&nbsp;" Then projekt = ""
Dim debettext As String = "0.00"
Dim kredittext As String = "0.00"
If row.Cells(3).Text.Length > 3 Then debettext = Replace(row.Cells(3).Text, ",", ".")
If row.Cells(4).Text.Length > 3 Then kredittext = Replace(row.Cells(4).Text, ",", ".")
Dim ptext As String = row.Cells(5).Text
If ptext = "&nbsp;" Then ptext = ""
Dim MySQLpost As String = "INSERT INTO Vpost (verid, kpnr, kst, projekt, debet, kredit, ptext) " & _
"Values (@verid, @kpnr, @kst, @projekt, @debet, @kredit, @ptext)"
Dim Cmdpost As New SqlCommand(MySQLpost, MyConn)
With Cmdpost.Parameters
.Add(New SqlParameter("@verid", p)) 'THIS SHOULD CHECK OUT AS WELL...
.Add(New SqlParameter("@kpnr", kpnr))
.Add(New SqlParameter("@kst", kst))
.Add(New SqlParameter("@projekt", projekt))
.Add(New SqlParameter("@debet", debettext))
.Add(New SqlParameter("@kredit", kredittext))
.Add(New SqlParameter("@ptext", ptext))
End With
Cmdpost.ExecuteNonQuery()
Next
MyConn.Close()
In other words, the verid is the id of the new post in the first table. This id should be inserted in the new table as well.
Thank you very much in advance fro helping me out! I've worked a LONG time with this.
Pettrer

View 3 Replies View Related

Scope Identity In SqlDataSource

Oct 15, 2007

Is it possible to write the InsertCommand for a SqlDataSource to return the value of the AUTONumber of a field generated when a new record is added to a database table and display that value on label1.Text after the postback of ItemInsersted event?  For example,  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NearMissConnectionString >" InsertCommand="INSERT INTO [NearMiss] ([Branch], [Division] VALUES (@Branch, @Division);  SELECT SCOPE_IDENTITY()" SelectCommand="SELECT [NearMissID], [Branch], [Division], FROM [NearMiss]"             <InsertParameters>                <asp parameter Name="Branch" Type="Int32" />                <asp parameter Name="Division" Type="String" />            </InsertParameters>
        </asp:SqlDataSource>
 
NearMissID would be the value of the autonumber generated by the SQL Server

View 1 Replies View Related







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