Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Tuesday, March 27, 2012

@@Identity not returning Value

I have a stored procedure that inserts a record. I call the @.@.Identity variable and assign that to a variable in my SQL statement in my asp.net page.

That all worked fine when i did it just like that. Now I'm using a new stored procedure that inserts records into 3 tables successively, and the value of the @.@.Identity field is no longer being returned.

As you can see below, since I don't want the identity field value of the 2 latter records, I call for that value immediately after the first insert. I then use the value to populate the other 2 tables. I just can't figure out why the value is not being returned to my asp.net application. Think there's something wrong with the SP or no?

When I pass the value of the TicketID variable to a text field after the insert, it gives me "@.TicketID".

Anyone have any ideas?


CREATE PROCEDURE [iguser].[newticket]
(
@.Category nvarchar(80),
@.Description nvarchar(200),
@.Detail nvarchar(3000),
@.OS nvarchar(150),
@.Browser nvarchar(250),
@.Internet nvarchar(100),
@.Method nvarchar(50),
@.Contacttime nvarchar(50),
@.Knowledge int,
@.Importance int,
@.Sendcopy bit,
@.Updateme bit,
@.ClientID int,
@.ContactID int,
@.TicketID integer OUTPUT
)
AS

INSERT INTO Tickets
(
Opendate,
Category,
Description,
Detail,
OS,
Browser,
Internet,
Method,
Contacttime,
Knowledge,
Importance,
Sendcopy,
Updateme
)
VALUES
(
Getdate(),
@.Category,
@.Description,
@.Detail,
@.OS,
@.Browser,
@.Internet,
@.Method,
@.Contacttime,
@.Knowledge,
@.Importance,
@.Sendcopy,
@.Updateme
)
SELECT
@.TicketID = @.@.Identity

INSERT INTO Contacts_to_Tickets
(
U2tUserID,
U2tTicketID
)
VALUES
(
@.ContactID,
@.TicketID
)

INSERT INTO Clients_to_Tickets
(
C2tClientID,
C2tTicketID
)
VALUES
(
@.ClientID,
@.TicketID
)

Fixed the problem, it was with my .net code|||The best practice is to constrain, you should use IDENT_CURRENT('Tickets') instead of @.@.IDENTITY when you are inserting into multiple tables. IDENT_CURRENT gives you the last Identity generated in a specific table, as @.@.IDENTITY has no constraint and returns the last Identity of any table in the session or scope.

Based on your execution @.@.IDENTITY will work, but I figured I would throw this out there anyway.

@@Identity in Stored procedure

Hi,

I have a stored procedure that insert data into 2 temp tables. The problem that I have is when I insert a data into a first table, how do I get the @.@.identity value from that table and insert it into the second table?? The following code is what I have:

Create #Temp1
@.StateID Identity,
@.State nvarchar(2),
@.wage money

INSERT INTO #Temp1 (State, wage)

SELECT State, Wage FROM Table1 INNER JOIN Table2 ON Table1.Table1_ID = Table2.Table2_ID

Create #Temp2
@.ID Identity
@.EmployeeID int
@.StateID Int
@.Field1 Money
@.Field2 Money

INSERT INTO #Temp2 (EmployeeID, StateID, Field1, Field2)

SELECT EmployeeID, StateID, Field1, Field2 FROM SomeTable

So, The first part I created a #Temp1 table and insert data into the table. Then after the insert, I want the @.@.Identity value and insert into the #Temp2 table. This is my first time doing stored procedure, so, I am wondering how do I retrieve the @.@.identity value and put into the second select statement. Please help.


ahTan

DECLARE @.NewID INT

SET @.NewID = @.@.IDENTITY

OR

DECLARE @.NewID INT

SELECT @.NewID = @.@.IDENTITY

|||

instead of @.@.IDENTITY use SCOPE_IDENTITY() like

declare @._ID int

Select @._ID = SCOPE_IDENTITY()

to know why to use it, please search for SCOPE_IDENTITY in SQL SERVER books online.

thanks,

satish.

|||

SCOPE_IDENTITY() is not necessary here since the table is being created in the same stored proc. There are no triggers that would be run or no side effects to doing an insert into the table, therefore @.@.IDENTITY will work fine.

SCOPE_IDENTITY() is useful when you may have a trigger that inserts into table2 when you insert into table1, in that case getting the value used in the IDENTITY column should be retrieved with SCOPE_IDENTITY() since @.@.IDENTITY will get you value from table2 and not table1. However you don't have to worry about that here.

Regards,

Tim

|||

Thank you guys for the answer. Now, the next problem is, how do I insert the @.@.Identity value into the #TempPayroll table?

|||

ahTan:

how do I insert the @.@.Identity value into the #TempPayroll table

just save the @.@.scope_identity from the first insert into another variable and use it as input to the 2nd insert

insert into table1....
select @.Identity1 = @.@.SCOPE_IDENTITY
insert into table2 (...) values(..., @.Identity1,...)

|||

Thank you all of you for the responses. I have managed to get the stored procedure to work when I tested it using the SQL analyzer. I am getting close to what I want. Ok, the stored procedure will be called using a sqldatasource. The following code call the stored procedure:

1For Each rowAs GridViewRowIn GridView1.Rows2 SqlDataSource2.InsertCommand ="_payroll"3 SqlDataSource2.InsertCommandType = SqlDataSourceCommandType.StoredProcedure4 SqlDataSource2.InsertParameters.Add("pniID", 410)5 SqlDataSource2.Insert()6 SqlDataSource2.InsertParameters.Clear()7Next8 GridView1.Visible =False9 SqlDataSource2.SelectCommand ="_payroll"10 SqlDataSource2.SelectCommandType = SqlDataSourceCommandType.StoredProcedure11''SqlDataSource2.SelectParameters.Add("pniID", CInt(row.Cells(0).Text.Trim))12 GridView2.DataSourceID ="SqlDataSource2"13 GridView2.DataBind()
After the for each loop, I want to display all the data in a gridview.  The following code is the sql code in the stored procedure:
 
1CREATE PROCEDURE [dbo].[_payroll]2(3@.pniIDint4)56AS78SET NOCOUNT ON910CREATE TABLE #TempStates11(12StateIDInt IDENTITY,13Statenvarchar(2),14Wagemoney15)1617Create Table #TempPayrolls18(19TempPayrollIDint IDENTITY,20PNI_IDint,21EmployeeIDint,22StateIDint,23Deptnvarchar(50),24PerDiemmoney,25Mileagemoney,26Phonemoney,27Computermoney,28Cameramoney29)3031INSERT INTO #TempStates (State, Wage)32SELECT PaySheets.StateOfProject,33 PNI_Payroll.Amount * PNI_Payroll.QuantityAS Amount34FROM PNI_Payroll35INNERJOIN PNION PNI_Payroll.PNI_ID = PNI.PNI_ID36INNERJOIN TimeSheetsON PNI.TimeSheetID = TimeSheets.TimeSheetID37INNERJOIN PaySheetsON TimeSheets.PaysheetID = PaySheets.PaysheetID38WHERE (PNI.PNI_ID = @.pniID)AND (PNI_Payroll.DescriptionLIKE'%Salary%')3940DECLARE @.NewStateIDint41SELECT @.NewStateID =@.@.IDENTITY4243--SELECT * FROM #TempStates4445INSERT INTO #TempPayrolls (PNI_ID, EmployeeID, StateID)46SELECT PNI.PNI_ID, InspectorID, StateID = @.NewStateID47FROM PNI48WHERE PNI.PNI_ID = @.pniID4950INSERT INTO #TempPayrolls (PNI_ID, EmployeeID, Dept, PerDiem, Mileage, Phone, Computer, Camera)51SELECT DISTINCT PNI.PNI_ID,52 PNI.InspectorID,53 StateOfProject +' Inspector'AS Dept,54 (SELECT (Quantity * Amount)As PerDiemAmtFROM PNI_PayrollWHERE PNI_ID = @.pniIDANDDescription ='Per Diem (YES OR NO)')AS PerDiem,55 (SELECT (Quantity * Amount)As MileageAmtFROM PNI_PayrollWHERE PNI_ID = @.pniIDANDDescription ='Mileage')AS Mileage,56 (SELECT (Quantity * Amount)As PhoneAmtFROM PNI_PayrollWHERE PNI_ID = @.pniIDANDDescription ='Cell Phone (YES OR NO)')AS Phone,57 (SELECT (Quantity * Amount)As ComputerAmtFROM PNI_PayrollWHERE PNI_ID = @.pniIDANDDescription ='Computer')AS Computer,58 (SELECT (Quantity * Amount)As DigitalCamAmtFROM PNI_PayrollWHERE PNI_ID = @.pniIDANDDescription ='Camera')AS Camera59FROM PNI_PayRoll60INNERJOIN PNION PNI_PayRoll.PNI_ID = PNI.PNI_ID61INNERJOIN TimeSheetsON PNI.TimeSheetID = TimeSheets.TimeSheetID62INNERJOIN PaySheetsON TimeSheets.PaysheetID = PaySheets.PaysheetID63WHERE PNI.PNI_ID = @.pniID6465--Display data from the temp tables66SELECT TempPayrollID, PNI_ID, EmployeeID,67(SELECT StateFROM #TempStatesWHERE #TempStates.StateID = #TempPayrolls.StateID)AS State,68(SELECT WageFROM #TempStatesWHERE #TempStates.StateID = #TempPayrolls.StateID)AS Wage,69PerDiem, Mileage, Phone, Computer, Camera70FROM #TempPayrolls717273-- Turn NOCOUNT back OFF7475SET NOCOUNT OFF76GO77
So, I am wondering how am I going to display all the data in the temp tables in the gridview2. Please help
|||

Satish is correct, use SCOPE_IDENTITY(). Although fevir's explaination is correct on why @.@.IDENTITY might work, it's misusing the command, and the wrong command to use.

Just because there are no triggers TODAY, doesn't mean that there won't ever be.

|||

Motley, what about the whole YAGNI thought? Today, as it sit, the temp table it being created directly above and so no triggers exits. If you eventually did put a trigger on a temp table (not sure why you'd do this) but you'd adjust at that time.

Ultimately you're correct in that either can be used, but I'm curious about your thoughts in regard the YAGNI argument.

Regards,

Tim

|||

YAGNI would only apply if there was an easy way and more difficult approach. Since we are talking about using:

SELECT @.NewStateID =@.@.IDENTITY

or

SELECT @.NewStateID =SCOPE_IDENTITY()

I see no point in using a function that really should be reserved for someone who is very well versed in T-SQL. It's rare that @.@.IDENTITY is the correct function to use when you need an identity value. Again, in this case, we want the identity value that was just inserted by the insert just above us. The function for that is SCOPE_IDENTITY. If we wanted to know the last identity value that the system generated in the scope of our connection, that would be @.@.IDENTITY. I have yet to EVER need @.@.IDENTITY in any project I've ever done. And while using @.@.IDENTITY can cause maintenaince problems, and unexpected results, the same is not true of SCOPE_IDENTITY. It will always return the result that we are expecting whether we have a trigger on the table today, tomorrow, or never.

I say this, because I can't count the number of times that people have gotten bitten because they had to add auditting tables to track changes to a table (or replication), only to find that the application is now creating bogus data because someone decided to use @.@.IDENTITY when they should have used SCOPE_IDENTITY().

@@Identity being over-written by Insert Trigger in stored procedure.

Hi All

I have a problem with an existing stored procedure that is used to insert a new entry to a table (using an Insert statement).

I have been using the @.@.Identity global variable to return the identity column (id column) back to the calling routine. This has worked fine for years until recently an after insert Trigger has been added to the table being updated.

Now the @.@.Identity is returning the identity value of the trigger that was called instead of the original table insert.

Does anyone know how I can code around this issue (without using a select statement within my stored proc, as these have been known to cause locks in the past).

Thank in advance.

Eamon.Look at SCOPE_IDENTITY and/or IDENT_CURRENT

Regards,

hmscott|||Thank you very much hmscott. SCOPE_IDENTITY works a treat!!!

@@identity

hi,

I was wondering if someone could help me out with this stored procedure I have. I am trying to execute a transaction in one of my sps and am getting pk violations on 'OrderID'.
This where i encounter this error:


SELECT
@.OrderID = @.@.Identity
/* Copy items from given shopping cart to OrdersDetail table for given OrderID*/
INSERT INTO OrderDetails
(
OrderID,
ProductID,
Quantity,
UnitCost
)
SELECT
@.OrderID,
ShoppingCart.ProductID,
ShoppingCart.Quantity,
Prices.UnitCost
FROM
ShoppingCart INNER JOIN
Prices ON ShoppingCart.ProductID = Prices.ProductID
WHERE
CartID = @.CartID

is there any way to rewrite this statement so that I can put it in the form insert()values(). ?is OrderID an autonumbering field?

if so - you shouldn't include it in your INSERT statement|||YEs it is ! Why do you not recommend putting it in the insert stetment ?

Anyways, I realized that my error wasn't really in the stored procedure, but in the function calling it.

Thanks.|||SQL will put the identity into the table automatically, what you're trying to do is over-write the value with the same number again...hence the duplicate key problem. So like the poster said, don't do it, get the help out and read what an identity column acutally is and how to use it.|||I'm not really overwriting the @.@.identity value, but assigning it to a variable. I then use the value of that variable in an insert statement on a totally separate table.
I solved my primary key issue and it wasn't related to the sql transaction i posted here, ....there was a logic error in my code.

So now even though its all working, you still think that the sql statement I'm using is incorrect ?|||Sorry I admit I was assuming the code that went before your example. The only suggest I would make would be to consider using SCOPE_IDENTITY rather than IDENTIY, tends to be safer in the long run.sql

@@identity

I have a problem hopefully someone can help with...
I have a stored procedure which ...
Writes to table A (table A has an identity column)
Gets the identity column using @.@.IDENTITY (OR @.@.SCOPE_IDENTITY)
Updates a table; setting column X to the IDENTITY value just retrieved
Table A has a couple of triggers on it, one of which writes to a different
table - and that table has an identity column.
Using either @.@.IDENTITY or @.@.SCOPE_IDENTITY I cannot get it to return the
identiy column for the table I wrote to (TABLE A), it returns the identity
value of the insert inside the triggers.
Any suggestions on how I get the correct value after writing to table A?
Hope this makes some sense!
Thanks> Using either @.@.IDENTITY or @.@.SCOPE_IDENTITY I cannot get it to return the
> identiy column for the table I wrote to (TABLE A), it returns the identity
> value of the insert inside the triggers.
There is a pretty good explanation in the BOL about how it works
If you insert a value into TableA by using @.@.scope_identity() function you
will get the last values of the identity column of the TableA
"..." <...@.nowhere.com> wrote in message
news:emnME2LAGHA.3496@.TK2MSFTNGP11.phx.gbl...
>I have a problem hopefully someone can help with...
> I have a stored procedure which ...
> Writes to table A (table A has an identity column)
> Gets the identity column using @.@.IDENTITY (OR @.@.SCOPE_IDENTITY)
> Updates a table; setting column X to the IDENTITY value just retrieved
> Table A has a couple of triggers on it, one of which writes to a different
> table - and that table has an identity column.
> Using either @.@.IDENTITY or @.@.SCOPE_IDENTITY I cannot get it to return the
> identiy column for the table I wrote to (TABLE A), it returns the identity
> value of the insert inside the triggers.
> Any suggestions on how I get the correct value after writing to table A?
> Hope this makes some sense!
> Thanks
>
>|||.... wrote:

> I have a problem hopefully someone can help with...
> I have a stored procedure which ...
> Writes to table A (table A has an identity column)
> Gets the identity column using @.@.IDENTITY (OR @.@.SCOPE_IDENTITY)
> Updates a table; setting column X to the IDENTITY value just retrieved
> Table A has a couple of triggers on it, one of which writes to a different
> table - and that table has an identity column.
> Using either @.@.IDENTITY or @.@.SCOPE_IDENTITY I cannot get it to return the
> identiy column for the table I wrote to (TABLE A), it returns the identity
> value of the insert inside the triggers.
> Any suggestions on how I get the correct value after writing to table A?
> Hope this makes some sense!
> Thanks
If you reference SCOPE_IDENTITY() in the proc then it will return the
last IDENTITY value inserted in the current scope (not in the trigger).
If you reference @.@.IDENTITY it will return the IDENTITY value from ANY
scope (including the trigger).
To reference the TableA IDENTITY value in the trigger itself don't use
either of those functions. Refer to the INSERTED virtual table instead.
Your trigger code should accommodate the fact that there may be more
than one row inserted.
There is no such function as @.@.SCOPE_IDENTITY.
David Portas
SQL Server MVP
--|||SCOPE_IDENTITY should work for you
If you want the latest identity regardless of scope and session then
take a look at IDENT_CURRENT
IDENT_CURRENT returns the last identity value generated for a specific
table in any session and any scope.
You would use it like this: SELECT IDENT_CURRENT('TableA') --TableA
would be your table name
http://sqlservercode.blogspot.com/|||not sure what @.@.scope_identity is -- SCOPE_IDENTITY() is the correct
function.
@.@.IDENTITY should have the last inserted identity value (the one
inserted into from the trigger)
SCOPE_IDENTITY() has last inserted identity from your session, so when
you check it, it should be as soon after the related insert as possible.
If this still doesn't help, could you post the proc and trigger code?
This will help posters give better answers.
... wrote:
> I have a problem hopefully someone can help with...
> I have a stored procedure which ...
> Writes to table A (table A has an identity column)
> Gets the identity column using @.@.IDENTITY (OR @.@.SCOPE_IDENTITY)
> Updates a table; setting column X to the IDENTITY value just retrieved
> Table A has a couple of triggers on it, one of which writes to a different
> table - and that table has an identity column.
> Using either @.@.IDENTITY or @.@.SCOPE_IDENTITY I cannot get it to return the
> identiy column for the table I wrote to (TABLE A), it returns the identity
> value of the insert inside the triggers.
> Any suggestions on how I get the correct value after writing to table A?
> Hope this makes some sense!
> Thanks
>
>

@@FETCH_STATUS

Hi there..
I have this problem: I run my stored proc alot of times for testing, but one
time it want work.
It just give me back this message: The command(s) completed successfully.
I checked the @.@.FETCH_STATUS and it became -1, why is that when it worked
before..
Can any body help me'
THX@.@.FETCH_STATUS is for cursors, you want to use @.@.ERROR instead if it's 0
then there is no error
http://sqlservercode.blogspot.com/
"Hussain Al-Mousawi" <hal_mousawi@.hotmail.com> wrote in message
news:uv6dVVTRGHA.2532@.TK2MSFTNGP10.phx.gbl...
> Hi there..
> I have this problem: I run my stored proc alot of times for testing, but
> one time it want work.
> It just give me back this message: The command(s) completed successfully.
> I checked the @.@.FETCH_STATUS and it became -1, why is that when it worked
> before..
> Can any body help me'
> THX
>

@@Error not catching error.

Hi all,

I want to catch error in stored procedure and return error message.
I want to catch error 'Syntax error converting the varchar value 'a'
to a column of data type int.' Means error occuring if i enter wrong
value.

Say suppose i have statment like

select * from emp where rowid = 'a'
PRINT @.@.ERROR
print 'reach'

here rowid is integer value so i am getting above mention error.

So what i am expecting is it should print error and then print 'reach'
which is not happening.
can anyone tell me reason behind this and how to overcome this
problem.

thanks in advance.(trialproduct2004@.yahoo.com) writes:

Quote:

Originally Posted by

I want to catch error in stored procedure and return error message.
I want to catch error 'Syntax error converting the varchar value 'a'
to a column of data type int.' Means error occuring if i enter wrong
value.
>
Say suppose i have statment like
>
select * from emp where rowid = 'a'
PRINT @.@.ERROR
print 'reach'
>
here rowid is integer value so i am getting above mention error.
>
So what i am expecting is it should print error and then print 'reach'
which is not happening.
can anyone tell me reason behind this and how to overcome this
problem.


If you are on SQL 2005, you need to use TRY-CATCH. If you are using SQL
2000, you first need to upgrade to SQL 2005. In SQL 2000 you cannot detect
this error, because the entire batch is aborted because of the error.
If you want to know more about error handling in SQL 2000, I have an
article on my web site: http://www.sommarskog.se/error-handling-I.html.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||(trialproduct2004@.yahoo.com) writes:

Quote:

Originally Posted by

I want to catch error in stored procedure and return error message.
I want to catch error 'Syntax error converting the varchar value 'a'
to a column of data type int.' Means error occuring if i enter wrong
value.
>
Say suppose i have statment like
>
select * from emp where rowid = 'a'
PRINT @.@.ERROR
print 'reach'
>
here rowid is integer value so i am getting above mention error.
>
So what i am expecting is it should print error and then print 'reach'
which is not happening.
can anyone tell me reason behind this and how to overcome this
problem.


If you are on SQL 2005, you need to use TRY-CATCH. If you are using SQL
2000, you first need to upgrade to SQL 2005. In SQL 2000 you cannot detect
this error, because the entire batch is aborted because of the error.
If you want to know more about error handling in SQL 2000, I have an
article on my web site: http://www.sommarskog.se/error-handling-I.html.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

@@ERROR logic not working

Hi There

I am having a little trouble with something very simple:

I have a stored procedure with the following sql in it:

UPDATE mfsWS_CustNewCustomer SET Result_Id = 0 WHERE QueryGUID = @.Guid

IF (@.@.ERROR <> 0)

BEGIN

RAISERROR ('Error setting Result_Id', 16, 1)

UPDATE mfsWS_CustNewCustomer SET Result_Id = 1 WHERE QueryGUID = @.Guid

RETURN

END

To test if this works i SET the Result_Id = 'X' this is a smallint column so this should not work.

My issue is that all i get is the error:

cannot convert char to numeric etc etc

However the @.@.ERROR logic is not executed , my error is not raised and the update does nto happen, it si as though the entire sp aborts at the point where i try do the bogus update.

Is there something i should SET at the beginning of my sp or something ? How do i ensure that any error will be passed to the logic that checks @.@.ERROR and performs the appropriate actions ? This is SS2000, so i cannot use try catch.

Thanx

Unfortunately, you can't. There isn't a way to trap any and all kinds of errors in your T-SQL code, since some errors terminates the batch. T-SQL code after the point where the error happens, never gets executed. In your case, a conversion error are of the 'breaking' kind.

You can verify with a small example. Note that the last line never gets printed.

declare @.i int
set @.i = 'x'
print 'Error happened'
go

Server: Msg 245, Level 16, State 1, Line 2
Syntax error converting the varchar value 'x' to a column of data type int.

In order to trap all kinds of errors, you need to trap the at the client (calling side) of the procedure. (if there is a 'client' of some sorts)

You can find more info on errorhandling here.
http://www.sommarskog.se/error-handling-II.html

/Kenneth

|||

Thanx Kenneth

So what can i do ?

What is the point of doing a IF (@.@.ERROR) check after a delete update or insert then?

I have to update a certain table to set the error code to 1 if an error occurs, is there no way to do this?

Thanx

|||

Well, it's a bit of a tight spot. T-SQL errorhandling possibilites are somewhat limited pre SS2005. The one certain point that all errors go to is to the 'client'. In the case of a procedure, the 'client' is whatever executed it. If this is another proc, then you still have the same problem. If it's some other 'external' program, then that's where all errors will land.

Please take some time and read through the link about errorhandling above. It's well spent time, I assure you. Errorhandling is like any other 'project', it needs afterthought and desicions must be made about what to do in various situations. It needs to be designed with understanding in order to serve it's purpose best - to give us robust and reliable code.

In this case, I don't think that the mission is impossible, but rather not as straightforward as we would like, due to the limitations and behaviour of some errors in T-SQL. But, to grant yourself some insight, and possibly a direction to go on how you want to handle your situattion, http://www.sommarskog.se/error-handling-II.html is a good place to start. =;o)

/Kenneth

|||

Thanx Kewin

I will definately read the link.

Yes it is a problem i have an sp that calls an sp, i have written it so that if @.@.ERROR <> 0 i RETURN @.@.ERROR and handle it in the calling sp, but in this case the execution will abort and not return the @.@.ERROR to the calling sp to be handled.

But let me first read the link and i will post again.

Thank You

|||

Hi Kewin

Am i correct in saying that my specific test which has to do with char to numeric implicit cast will cause execution to abort BUT if the update or insert for example violated a primary key constriant or something more general that the execution would continue and execute the T-SQL in the IF @.@.ERROR <> 0 logic ?

|||Correct. Not all errors are transaction aborting or batch aborting errors. For example, syntax errors or compile-time errors cannot be caught with exception handling in SQL Server 2005 also. Please check out Erland's home page and the error handling topics in BOL.|||

To add a pennies worth, the big twist to error handling (even in 2005, though you have the control of try...catch) is the client. If you have a well behaved client like Query Analyzer or SSMS, then the IF@.@.error logic is very important, because it will always return control after an error if the error is not batch terminating. However, almost every client I see stops executing on an error and ends the batch itself. In those cases it is important to handle the errors with that in mind.

Things like

<DML operation>

if @.@.error <> 0
begin
raiserror ('boom',16,1)
rollback transaction
return -100
end

Look good, but if the client never completes the message and returns control, you can be stuck with an open transaction. And even worse, you probably never reach the raiserror, rollback, or return if the error in the DML operation occurs.

But you have to be ready for it nevertheless...

|||

Thanx for all the feedback guys.

I have read the link Kewin and i know most of it but l did learn one or 2 new things, thanx.

I guess what i am really trying to ask is as far as SS2000 goes there is not anything more i can do in an stored procedure than :

IF @.@.ERROR <>0

BEGIN

RASIERROR

ROLLBACK TRAN

RETURN -1

END

These sp's are called by a .Net app i understand completely that the app must be ready for any kind of exception.

What i really want to confirm is that there is nothing more or better i could do from an sp error handling point of view?

Thanx

|||

You got it.
Basically, that's what is avaliable to us as far as errorhandling in T-SQL on SS 2000 goes.

A workaround of sorts around these limitations can be done, and when I think about it, that's pretty much what 'scrubbing' is all about. For known 'fatal' errors that you know you can't trap, and possibly could leave you in some sticky situation, it's common to try to ensure that the situation never happens, either by first validating thoroughly, or by different coding techniques.

eg, to avoid a PK violation when inserting a new row, you could first check for the existence, or (perhaps even better) do the insert based on a left joined select. In the latter case, if the PK didn't exist, 1 row would be affected, but should it already exist, 0 rows would be affected. But more importantly, it's not an error to do some DML and have zero rows affected. Approaching a problem from different angles may be of aid to circumvent some of the errorhandling limitations that we have.

/Kenneth

sql

Sunday, March 25, 2012

@@CPU_BUSY stops incrementing and generates "Arithmetic overflow occurred"

I am using several globals including @.@.CPU_BUSY to log the performance of some stored procedures. It works fine on my dev server, but in production the value reported by @.@.CPU_BUSY on my production server has stopped at 134217727. And when I try to assign its value to a variable, it always generates an error.

For example:

DECLARE @.FOO BigInt
Set @.foo = @.@.CPU_BUSY
print @.Foo


generates

Arithmetic overflow occurred.
134217727

Note that

DECLARE @.FOO BigInt
Set @.foo = 134217727
print @.Foo


works fine.

I understand that when the value of @.@.CPU_BUSY reaches a certain point, its value becomes inaccurate according to MSDN TSQL Reference. I've also seen some descriptions that say the value is supposed to "wrap" back to zero.

So the questions are:
Is the value of @.@.CPU_BUSY supposed to wrap back to zero when it overflows?
Is there a better/more reliable way to do this?

Cheers,
Jeff
by the way:
Select @.@.version
Microsoft SQL Server 2000 - 8.00.760 (Intel X86)
Dec 17 2002 14:22:05
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 4)sql

Can you save XML to a Database?

The XML generated by notifications object needs to be saved. Where do I save it - in the database. That will still be stored in a table - with drawbacks!Not sure what the question is. You can save XML to a database or to a file.|||Sorry, I meant to say what does Integration services do when I deploy the project? Does it use XML to write to the database or the file system?|||You can store the packages in either the file system or the SQL Server MSDB database, your choice.|||How do I define the choice for later only database format? Is that something I have to specify as properties from Analysis services?|||I'm sorry, but I'm not sure what this has to do with Analysis Services. I'm talking about SSIS packages (files with a .dtsx extension). These can be deployed to either the database or the file system - you can't enforce that they are only deployed to one or the other when you are building the package. That's really an issue for your organization's policies and procedures.sql

Can you save XML to a Database?

The XML generated by notifications object needs to be saved. Where do I save it - in the database. That will still be stored in a table - with drawbacks!Not sure what the question is. You can save XML to a database or to a file.|||Sorry, I meant to say what does Integration services do when I deploy the project? Does it use XML to write to the database or the file system?|||You can store the packages in either the file system or the SQL Server MSDB database, your choice.|||How do I define the choice for later only database format? Is that something I have to specify as properties from Analysis services?|||I'm sorry, but I'm not sure what this has to do with Analysis Services. I'm talking about SSIS packages (files with a .dtsx extension). These can be deployed to either the database or the file system - you can't enforce that they are only deployed to one or the other when you are building the package. That's really an issue for your organization's policies and procedures.

Sunday, March 11, 2012

.Net Stored Procedures on IA64 SSAS

Does anybody know if it is possible to call .Net stored procedures from a 64 bit Analysis Services Installation? Unfortunately the .Net stored procedures which we are trying to use target the x86 platform and not IA64.

(The procedures use an ODBC driver that is only available to 32 bit applications.)

Any information would be appreciated. The trial and error process gives me an MDX error that says that my stored procedures cannot be found. However, SSAS lets me add the x86 assembly to my database without any problem.

You can't cross 32/64 bit process boundaries within a single process this way. You can't try to load 32bit stored procedure into 64 bit process. Analysis Server is not checking the target platform you compiled you SP for on load, but later as you can see it fails to load it.

If you absolutely must to use the 32bit ODBC driver, you have an option of installing 32bit AS on 64bit platform. But that is highly unintuitive. Take a look if you can find native 64bit version of OLEDB provider instead of using 32bit ODBC driver.

Edward.
--
This posting is provided "AS IS" with no warranties, and confers no rights.

|||I also would like to add here, that unless you are using COM based sprocs (which are off by default), the .NET sprocs are platform agnostic, just like .NET itself. You can take sproc .NET assembly and deploy it to either 32 or 64 bit server without recompilation - it should work fine.

.net Security Exception

I am trying to access a stored proc from windows app (VS 2005 running on windows 2003 server).

The code is

SqlConnection conn = new SqlConnection(sCn);

SqlCommand command = new SqlCommand(sCmd, conn);

SqlDataAdapter adapter = new SqlDataAdapter(command);

DataSet ds = new DataSet();

adapter.Fill(ds, "Location");

this.dg.DataSource = ds;

this.dg.DataMember = "Location";

I get the following exception!!!

System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
at WindowsApplication1.Form1.Form1_Load(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Data.SqlClient.SqlClientPermission
The Zone of the assembly that failed was:
Internet

What am I doing wrong?

Thanks

SqlCommand command = new SqlCommand(sCmd, conn);

SqlDataAdapter adapter = new SqlDataAdapter(command);

what exactly is command refering to?

Secondly, if it's refering to a networked application, you probably have to publish the assemblies via caspol on the server.

Based on the error, you need to add a key for the Internet codebase.

Thursday, March 8, 2012

.Net passing bad formatted value to stored procedure

Hi, that's the problem:

I have a GridView, bound to a SQLDataSource, with an stored procedure as a Select query. The Select Parameters are bound to controls in the web form, acting like some filter fields.

When I submit the page, everythings works fine, except when I try to set some value in the DateTime fields. .Net is enclosing the date with extra single quotes, as I could see in the Profiler:

exec sel_despesa_procura @.codigo=NULL,@.fornecedor=NULL,@.descricao=NULL,@.vencto_ini=''2005-10-10 00:00:00:000'',@.vencto_fim=''2005-10-20
00:00:00:000'',@.pagto_ini=NULL,@.pagto_fim=NULL,@.valor=NULL,@.valor_pago=NULL,
@.centro_custo=NULL,@.pago=N'0,1'

The fields are defined as follows:

<SelectParameters>
...
<asp:ControlParameterControlID="txtFiltroVencIni"Name="vencto_ini"PropertyName="Text"Type="DateTime"/>
<asp:ControlParameterControlID="txtFiltroVencFim"Name="vencto_fim"PropertyName="Text"Type="DateTime"/>
...
</SelectParameters>

The stored procedure doesn't even execute, due to the bad formatted arguments. It returns the error:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '2005'.

I'm going to change the parameter type to varchar, as a workaround, but I'd like to solve this problem.

Thanks in advance,

Anderson

That is not it's normal behavior. Just for laughs, set the pages culture and uiculture to "en-US", and run the page again and see if the problem disappears. If it does, then it's a bug with your particular culture settings.

.Net interface to vss for sql 2000 stored procedures

We would like to use the version control for sql stored procedures through
.net, however, according to Microsoft's implementation procedures it gives
developers "sa" authority. Does anyone know how we can set this up without
the developers having "sa" authority on our database?You can use Windows Authentication for developers staff
"sgerwie" wrote:

> We would like to use the version control for sql stored procedures through
> .net, however, according to Microsoft's implementation procedures it gives
> developers "sa" authority. Does anyone know how we can set this up without
> the developers having "sa" authority on our database?|||We do use Windows Authentication for the developers, however, in order to se
t
this up, SQL services has to run with "sa" authority and Admin rights on the
server, therefore, it automatically gives everyone "sa" rights to SQL. It
doesn't matter
"MAURICIO" wrote:
[vbcol=seagreen]
> You can use Windows Authentication for developers staff
> "sgerwie" wrote:
>

Tuesday, March 6, 2012

.NET CLR stored procedure capabilities

I've want to create a typed DataSet and use it inside a .NET CLR stored
procedure. But the option to add a typed DataSet to the project
doesn't exist. Am I missing something? Or are .NET CLR stored
procedures not all they're hyped up to be?
Todd
toddpiltingsrud@.altoconsulting.com wrote in
news:1132776964.626979.93470@.g47g2000cwa.googlegro ups.com:

> I've want to create a typed DataSet and use it inside a .NET CLR
> stored procedure. But the option to add a typed DataSet to the
> project doesn't exist. Am I missing something? Or are .NET CLR
> stored procedures not all they're hyped up to be?
Course you can create a typed DataSet and use it in SQLCLR. Younhave to
create it manually though instead of drag 'n drop.
Just out of curiousity; why do you want a typed dataset inside SQL
Server?
Niels
**************************************************
* Niels Berglund
* http://staff.develop.com/nielsb
* nielsb@.no-spam.develop.com
* "A First Look at SQL Server 2005 for Developers"
* http://www.awprofessional.com/title/0321180593
**************************************************

.NET CLR stored procedure capabilities

I've want to create a typed DataSet and use it inside a .NET CLR stored
procedure. But the option to add a typed DataSet to the project
doesn't exist. Am I missing something? Or are .NET CLR stored
procedures not all they're hyped up to be?
Toddtoddpiltingsrud@.altoconsulting.com wrote in
news:1132776964.626979.93470@.g47g2000cwa.googlegroups.com:

> I've want to create a typed DataSet and use it inside a .NET CLR
> stored procedure. But the option to add a typed DataSet to the
> project doesn't exist. Am I missing something? Or are .NET CLR
> stored procedures not all they're hyped up to be?
Course you can create a typed DataSet and use it in SQLCLR. Younhave to
create it manually though instead of drag 'n drop.
Just out of curiousity; why do you want a typed dataset inside SQL
Server?
Niels
****************************************
**********
* Niels Berglund
* http://staff.develop.com/nielsb
* nielsb@.no-spam.develop.com
* "A First Look at SQL Server 2005 for Developers"
* http://www.awprofessional.com/title/0321180593
****************************************
**********

.NET CLR stored procedure capabilities

I've want to create a typed DataSet and use it inside a .NET CLR stored
procedure. But the option to add a typed DataSet to the project
doesn't exist. Am I missing something? Or are .NET CLR stored
procedures not all they're hyped up to be?
Toddtoddpiltingsrud@.altoconsulting.com wrote in
news:1132776964.626979.93470@.g47g2000cwa.googlegroups.com:
> I've want to create a typed DataSet and use it inside a .NET CLR
> stored procedure. But the option to add a typed DataSet to the
> project doesn't exist. Am I missing something? Or are .NET CLR
> stored procedures not all they're hyped up to be?
Course you can create a typed DataSet and use it in SQLCLR. Younhave to
create it manually though instead of drag 'n drop.
Just out of curiousity; why do you want a typed dataset inside SQL
Server?
Niels
**************************************************
* Niels Berglund
* http://staff.develop.com/nielsb
* nielsb@.no-spam.develop.com
* "A First Look at SQL Server 2005 for Developers"
* http://www.awprofessional.com/title/0321180593
**************************************************

.Net 2.0 and datetime

Hi,

Here's my problem.

So using a stored proc and some parameters I want to update a datetime field

So I define @.theDate as datetime in my stored proc

in my vb.net app I have

dbcmd.Parameters.AddWithValue("@.theDate", SelectedDate)

where SelectedDate is

Dim SelectedDate as Nullable(of Datetime)

Now if SelectDate is a value all is good with the world.

However if SelectDate is Null I get an error.

How do I pass a null date to the stored proc ?

You need to add code like this:

dbcmd.Parameters.AddWithValue("@.theDate", (SelectedDate==null) ? DbNull.Value : SelectedDate)

DbNull.Value is a null for the database.

Friday, February 24, 2012

.exe from stored procs

Hey guys.

I am wondering if it is possible to execute an .exe from a stored proc. I have an application that calls a stored proc and I am wanting for that stored proc to call up an app to show certain results. I have no way of doing this on the application itself as I dont have the source code. So, since I do have access to the SQL I am wondering if it could be done there.

Thanks
tiboryou can launch an exe from a proc with xp_cmdshell. you can't display any of it's output though, except for whatever it writes to stdout.

if it's a GUI app, there's no point to it. Also, remember that this app would have to be located on the server.

Be very careful with this. If you enable xp_cmdshell, it opens up a fairly large security hole on your db server. Make sure only appropriate logins have perms to execute it. don't give any clients permissions to execute it directly or you may find that a criminal has stolen all your data.|||It's not advisable

You could bring down the server from what I understand

But if you want to try you need to use master..xp_cmdshell

But if you don't know about the sproc, then I'd really advise against it|||Thanks guys

Turns out, I may be able to avoid the project in its entirety but this is good info to know for the future.

Again, very much appreciated :)|||just be careful if you ever decide to use it. xp_cmdshell is a cross between a loaded gun and a vial of nitroglycerin.|||just be careful if you ever decide to use it. xp_cmdshell is a cross between a loaded gun and a vial of nitroglycerin.

pffffftttttt

The real danger is trying to launch an application with it

Hey DROP Database is kinda dangerous as well|||the real danger is that you can use xp_cmdshell to do anything you could do from a command prompt, which is pretty much anything.

if the wrong people have rights to execute xp_cmdshell, you are in trouble. so best left disabled.|||if the wrong people have rights to execute xp_cmdshell, you are in trouble.

Of course, would you give a gun to a toddler?

so best left disabled.

Couldn't disagree more|||Tibor, don't listen to Brett.

he's a wild vocalist (http://www.rockdetector.com/artist,5489.sm) for an all-girl 80's hair-metal band. everyone knows such types can't be trusted.

:)|||belly aching laughter. on the floor. verge of tears.

but really if your shop is not locked down with regards to db server security, shame on you. Although I have been somewhere that refused to be locked down. So I left.

I find xp_cmdshell extremely useful especially combined with osql. I do my database builds that way by doing a fresh dump from source control and letting those rip with a little cursor and some logging. A little Redgate afterwards to be sure and everything is right as rain.|||Hi,

I've quite the same Problem as Tibor.
I also try to call a .exe from a trigger.
The .exe is a VB.Net command line application, that shall invoke a ETL script on a third party BI Application. The VB application first calls the getObject Function and then calls the Reload Function of the BI application.
This application works fine, when I start it in the command line.
But when I try to call it with the xp_cmdshell proc the execution stucks and after a while an exception is thrown ("ActiveX component couldn't be started" or so on)
Until now, I haven't found any way to fix this problem.
Now I'm searching for another way of calling an .exe from a trigger. I don't know, if this helps. Maybe you have any suggestions to deal with this problem
Thanks in advance

Gojo|||you want to call an exe from a trigger? pardon me, but that's a less than good idea. It's quite bad actually.

triggers need to have a very constrained scope - they shouldn't be launching other processes, sending emails, writing data to remote servers, calculating your horoscope, or anything like that.

if you do somehow figure out how to launch an exe from a trigger, the perf or your application will suffer big time.

what are you trying to achieve with this? why do you think launching an exe is the way to do it?|||triggers need to have a very constrained scope - they shouldn't be launching other processes, sending emails, writing data to remote servers, calculating your horoscope, or anything like that.

If you're using SQL Server 2005, you can use the Service Broker to do such "crazy" stuff without ending up with long running transactions.|||Thanks for the fast replies

@. jezemine
I know, the idea sonds weird. My problem is, that I want to keep my data in the dashboard event triggered.
In this case a new DB entry is a event. But when I'm constantly polling the table (as I do now) the solution isn't event triggered. The only way to achieve this, is to call the .exe (which calls the load script), when there is a new entry in the table (therefore the trigger).
Do you have another idea how to accomplish that (I mean how to tell my .exe that there's a new entry, so that the .exe can call the load script)?

@.kaffenils
Unfortunately I have to use the 2000 version

thanks
gojo|||you could write an app that polls the table every so often, and when there's a new row then it executes your load script.

I don't understand what you mean by "the solution isn't even triggered" btw.|||Currently I poll the table every 5 secs. If there's a new row, I execute my script. This works fine, but as I wrote before, this solution is not what I actually want.
I don't want a permanent polling. I want the new Table entry to be the "initiator" of the script execution. When I poll the table, the poll query is the "initiator".
I hope I could make clear, what I want.

thanks
gojo|||Maybe my Problem could be solved another way.
Is there a possibility in SQL Server 2000 to access a class which is written in .NET and which is "stored" in the Global Assembly Cache (GAC)?
Then I could access the reload command.

Thanks gojo|||I'd probably create a SQL Agent job that did whatever "heavy lifting" was required (running the ETL process, etc), then use either sp_start_job (http://msdn2.microsoft.com/En-US/library/aa260289(SQL.80).aspx) or some closely related form of trickery to actually start the job itself.

-PatP|||note that would fail if the job is already running. you can't have two instances of the same job running at once.|||Thanks for the replies.
I've found an interesting site.
http://sqljunkies.com/Article/C5A500EB-B8BE-42C0-B23B-258A342CAAAB.scuk
I think that's exactly what I want.
I hope it works.

thanks gojo|||invoking that kind of thing from a trigger still counts as a no-no in my book.|||I agree, that this shouldn't be implemented in practice.
In my case this solution is more a feasibility study, if that kind of idea (new entry as trigger of a new Data Load) can be implemented in a technical way.|||note that would fail if the job is already running. you can't have two instances of the same job running at once.Failure to start the second instance would be a bad thing? I can't imagine a case where you'd want two separate ETL loads running at once. I suppose that you could queue the subsequent jobs somehow if there was any chance that you really wanted that to happen.

-PatP|||I have no idea if that would be a bad thing or not - depends on OP's requirements. I just stated is as a fyi for the OP.|||Ok so I have been playing around some with xp_cmdshell(yes, I know...not good, lol) but when I run the .exe, my query analyzer hangs up for about 10 minutes.

exec master..xp_cmdshell 'C:\test.exe'

It is just a little vb app i created to test with but it hangs up and does not execute.

I know that I have permissions and such as i can do a simple dos directory seach with it.

Any ideas as to why it hangs up?

Thanks|||It seems to be running it in the processes list of task manager but not actually running the application. Is it possible to actually run the app?|||If your application is expecting someone to click an OK button, you will be waiting a long time.|||Yeah, I just found out that it wont allow it...so i withdraw my question. heh|||If your application is expecting someone to click an OK button, you will be waiting a long time.. ;)|||If your application is expecting someone to click an OK button, you will be waiting a long time.

really? whenever I write a trigger, i have it pop a message box to ask the user if they really want to commit the data. it works great!

:)|||In order to pass a moderate SOX audit, you would have to ask that question twice. "Are you sure you want to commit that data?" "Really sure?"