Quantcast
Channel: SQL Server Data Access forum
Viewing all 4164 articles
Browse latest View live

How does the Identity Column really work?

$
0
0

I am having an issue with an application using SQLServer 2008. My app has a class called SalesInvoice. I use ADO and VB6 for my app.

The Index value for the record is the "Sales Invoice Number" which was created as an Identity_Spec with an increment of one. It was created using SSMS. It is set as the Primary Key and is Unique. It is a bigint data type.

I have discovered in Microsoft documentation that the identity increment might get lost.  (See the quote copied form the help file.)

"The identity property on a column does not guarantee the following:

  • Uniqueness of the value– Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint orUNIQUE index.

  • Consecutive values within a transaction– A transaction inserting multiple rows is not guaranteed to get consecutive values for the rows because other concurrent inserts might occur on the table. If values must be consecutive then the transaction should use an exclusive lock on the table or use the SERIALIZABLE isolation level.

  • Consecutive values after server restart or other failures–SQL Server might cache identity values for performance reasons and some of the assigned values can be lost during a database failure or server restart. This can result in gaps in the identity value upon insert. If gaps are not acceptable then the application should use its own mechanism to generate key values. Using a sequencegeneratorwith the NOCACHEoption can limit the gaps to transactions that are never committed.

  • Reuse of values– For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated."

There is no issue with consecutive values within a transaction, although each invoice is written out in a transaction, as it is paired with Sales Line detail records. They are linked using the Sales Invoice Number.

The issue comes in with the line " udtProps.InvoiceNumber = .Fields("Invoice Number")" as this is the property that returns the sales invoice number to the app that is used to actually print the invoice.

My problem is with the 3rd bullet point from the help file. "Consecutive values after server restart or other failures", particularly the "Other Failures" as they are not defined.

I have pasted the sub from the class that actually persists the record, below. It includes the Error handler routine. Ia particularly concerned that the case of the Database record lock conflict error might be one of the "Other Failures" described in the help file above. In at least One occasion, the invoice printed with an invoice number of 690172, but was written to the database with an invoice number of 690175.

If anybody has an in depth understanding of when the identity spec invoice number is set, returned and incremented, please help. Is it the first time the update is tried, or when the update command completes successfully?

Private Sub Save()
    On Error GoTo ErrorHandler
    iRecLockReTry = 0
    
    Dim rs As ADODB.Recordset
    Dim sSQL As String
    
    Set rs = New ADODB.Recordset

    sSQL = "SELECT * FROM [Sales Invoices] "
    sSQL = sSQL & "WHERE [Invoice Number] = " & udtProps.InvoiceNumber
    
    If cnCompany.State = adStateClosed Then
        cnCompany.Open
    End If
    
    With rs
        .ActiveConnection = cnCompany
        .CursorLocation = adUseClient         
        .CursorType = adOpenDynamic
        .LockType = adLockPessimistic
        .Open sSQL
    End With
    
    If bNew Then rs.AddNew
    
    With rs
      ... (Values set here)

        .Update

        If bNew Then
            ' update ID property similar to below when adding record for first time
            udtProps.InvoiceNumber = .Fields("Invoice Number")
        End If

        .Close

    End With

    Set rs = Nothing
 
    Exit Sub
ErrorHandler:
    If Err.Number = otErrorDBUpdateConflict Then
'        Err.Raise 61002, sClassName, "Another user has updated this record while you were looking at it. You will have to recall the record and re-enter your changes."
        objError.ErrorHandle ERROR_CLASS_ID, otGeneralUpdateConflict, otErrorWarning
        'The way we are handling things I can't see how we would ever get this error. But Microsoft has it in as an error so it must be possible...
    ElseIf Err.Number = otErrorDBRecordLockConflict Then
        While iRecLockReTry < otErrorConstRecordLockRetry
            iRecLockReTry = iRecLockReTry + 1
            rs.Requery
            Resume
        Wend
'        Err.Raise 61001, sClassName, "Another User has this record Locked. Do you wish to Continue trying to update?"
         objError.ErrorHandle ERROR_CLASS_ID, otGeneralRecordLockConflict, otErrorWarning
   ElseIf Err.Number = otErrorDBDuplicateIndex Then
'        Err.Raise 61003, sClassName, "Unable to update this record because one of the fields has a duplicate index conflict. Please resolve the issue and try again."
         objError.ErrorHandle ERROR_CLASS_ID, otGeneralDuplicateIndex, otErrorWarning
    Else
'        Err.Raise Err.Number, sClassName & "." & "Save", Err.Description, Err.HelpFile, Err.HelpContext
         objError.ErrorHandle ERROR_CLASS_ID, otGeneralUnexpectedDatabaseError, otErrorFatal
    End If

                        

With women, the TRUTH will not only NOT set you free, it will cause you a great deal of trouble.


Help required to fetch records from a table where there is a matching key and write into another file in SQL Server...

$
0
0

Hi All,

I have a set of millions of records that I would need to compare it with a master table and select few additional fields (if the data field is NOT NULL) and write those two fields into another xls file.

What would be the query/ command that I can use to WRITE the records that having matching key values from my input data with the records in the xls file? Immediate response would be very much appreciated.

Regards

I can't pass empty string as column of Table Valued Parameter.

$
0
0

Hello.

I have stored procedure which accept TVP with columns of 'sql_variant' type. And I have C++ application which call this stored procedure.

When i pass some non-empty string as sql_variant from my application - all works fine.

But when I need to pass empty string ("") as sql_variant - I get following error:

"OLEDB hr = 0x80040e14
[
 #0:  OLEDB provider error 3621  "The statement has been terminated."
 #1:  OLEDB provider error 8062  "The data for the table-valued parameter 1 doesn't conform to the table type of the parameter."
 #2:  OLEDB provider error 8046  "The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 0 (""), row 1, column 1: The supplied length is not valid for data type sql_variant. Check the source data for invalid lengths. An example of an invalid length is data of nchar type with an odd length in bytes."  
]"

Could you please help me deal with that issue?

Thanks,

Vitaliy

Issues with DB after upgrade to SQL 2012

$
0
0

Dear All, 

          I am in charge of maintaining a delphi application that connects to MS SQL Server via ADO.

This application has been working fine on  MS 2003 Server using SQL 2005.

 Recently we had bought some blade server and decided to upgrade.

We started by first upgrading to OS to 2012 R2 and then upgraded  SQL Server to 2012 then attached the database.

Since then we have getting inconsistent results from an app that has been working flawlessly for the past 6 years.

Upon doing some profiling I noticed SQL is not using the values of the parameters the client application assigns it.

For instance for a particular inserts irrespective of the value the client application assigns the parameter SQL server always uses that value 17.  This is causing use lots of sleepless nights.

Can some one please tell me what is happening here ?

Actually I have considered going back to SQL 2005 but I am not sure if I can attach the database to it since I do not think the files are backward compatible. 

Please help me I am desperate.

Thanks in Advance.


How to create linked server in sql 2005 to access free table visual foxpro 9 step by step

$
0
0

Hi All, I want to connect to dbf file visual foxpro by using linked server in sql 2005, but i can't do, i hope getting best anwser from every body in forum.

Thanks all.

SQL Job Steps not able to View or Edit

$
0
0

Hi, When I try to open the SQL jobs, I'm not able to view or edit the same.

I'm just getting the error "No Description Found". I'm facing the same problem for all the jobs configured in the SQL server.

Even I checked with the User Roles assigned and everything is perfect (assigned with sysadmin role even), but still facing the same problem. Could you please help me out of this ?

Thanks in Advance!!

SQL Update the date portion of a datetime field

$
0
0

Hello,

I need a SQL statement to update the date portion of a datetime field.  For example I need to change

'2014-08-07 21:28:44.000' to '2014-08-23 21:28:44.000'

THank you

SQLNCLI11 - Recordset with Server Side cursor and Property PreserveOnCommit = TRUE

$
0
0

I am migrating an OLEDB application from Microsoft Access to SQL.  I am using the SQL Native Client in my connection string

"Provider=SQLNCLI11;Server=%s;Database=%s;Trusted_Connection=yes;"

The application uses the following call to open a table in the database

m_pRecordset->Open((LPCTSTR)m_strQuery, _variant_t((IDispatch*)mpdb, TRUE), adCursorType, adLockOptimistic, options);

where m_strQuery is the table name, adCursorType is adOpenKeyset or adOpenDynamic (I've tried both), options is adCmdTable or adCmdTableDirect (I've tried both)

mpdb is a _ConnectionPtr.  Cursor location can be either adUseClient or adUseServer.

If I set Cursor location to adUseClient, the PreserveOnCommit Property of the  Recordset is true; if I set Cursor location to adUseServer the PreserveOnCommit property of the Recordset is false.  I cannot set this property after the recordset is open

Is there a way to Open the recorfdset with a server side cursor and PreserveOnCommit TRUE?


Howard P. Weiss


Query to count no.of orders using joins and subqueries

$
0
0

I have 3 tables i want to show the no. of orders when order placed date is equal to Create date(user registered date)

order table contains following columns

[OrderId]
      ,[UserId]
      ,[OrderPlaced]
      ,[Paid]
      ,[DatePaid]
      ,[PaymentMethod]
      ,[PaymentRef]
      ,[BillTo]
      ,[AddressLine1]
      ,[AddressLine2]
      ,[City]
      ,[County]
      ,[CountryId]
      ,[PostCode]
      ,[Shipped]
      ,[DateShipped]
      ,[Packing]
      ,[ShipTo]
      ,[ShippingAddressLine1]
      ,[ShippingAddressLine2]
      ,[ShippingCity]
      ,[ShippingCounty]
      ,[ShippingCountryId]
      ,[ShippingPostCode]
      ,[ShippingCost]
      ,[ShippingOptionId]
      ,[AllocatedPoint]
      ,[PointValue]
      ,[PromoCode]
      ,[DiscountValue]
      ,[InvoiceNumber]
      ,[IPAddress]
      ,[StatusCode]
      ,[IssueCode]
      ,[USStateId]
      ,[ShippingUSStateId]
      ,[CurrencyCode]
      ,[ExchangeRate]
      ,[LastActivityDate]
      ,[AwardedPoint]
      ,[Archived]
      ,[LastAlertDate]

aspnet_Membership table contains

[Password]
      ,[PasswordFormat]
      ,[PasswordSalt]
      ,[MobilePIN]
      ,[Email]
      ,[LoweredEmail]
      ,[PasswordQuestion]
      ,[PasswordAnswer]
      ,[IsApproved]
      ,[IsLockedOut]
      ,[CreateDate]
      ,[LastLoginDate]
      ,[LastPasswordChangedDate]
      ,[LastLockoutDate]
      ,[FailedPasswordAttemptCount]
      ,[FailedPasswordAttemptWindowStart]
      ,[FailedPasswordAnswerAttemptCount]
      ,[FailedPasswordAnswerAttemptWindowStart]
      ,[Comment]

Account table contains 

[UserId]
      ,[FirstName]
      ,[LastName]
      ,[Email]
      ,[ContactNumber]
      ,[DOB]
      ,[Note]


my code is

SELECT a.UserId, m.Email, o.OrderPlaced, o.OrderId, m.CreateDate
FROM Account a, aspnet_Membership m, Orders o
where a.UserId=o.UserId and a.Email=m.Email ORDER BY a.UserId 

I had displayed the required details using joins but now i want the number of orders when order placed date is equal to Create date(user registered date)

can anyone help me iam a fresher

Thanks in advance.

Linked Server error

$
0
0

Hi,

I have configured linked server for Oracle. The linked server is fine and I am able to test the connection to succeed, also able to drill down all Tableds and Views from the Linked server

I have also checked 'Allow Inprocess' for the Ora.OLEDB.Oracle provider


But when I execute an OPEN QUERY,

Select * from
openquery (CISL,'SELECT * FROM Tab1
group by Col1 ORDER BY Col2 ')

I get the below error
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "OraOLEDB.Oracle" for linked server "CISL" reported an error. Access denied.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "OraOLEDB.Oracle" for linked server "CISL".


The below openquery does work, and is able to retrieve data.
Select * from
openquery (CISL,'SELECT * FROM Tab1)


What is wrong with the first query. This works on another server with SQL Server 2005


Thanks,

Question about retrieving data from two tables

$
0
0

Hi everyone.

I've been working on this and was wondering what the correct way of handling this would be.

I have two tables, a Billing Table that contains invoices and related information, and a Payments Table that contains payments and related information to that.

Both tables contain a Date Column for the date that the Invoice was generated or the Payment was made.

I want to get a list of all Invoices and the respective payments if the invoice was generated between two dates OR the payment was made between these two dates.

I can get a list of the invoices and their payments if the invoice was generated between those dates.  I can get a list of the payments if they were made between those dates.  But I can't seem to figure out how to do both.

How do I Join two tables and have it return the data from both tables if either meets the required Date Period?

Here is the SQL that I have so far.  This SQL returns all of the Invoices and Payments IF the Invoice was generated between these two dates (Or updated). 

SELECT Billing.ID AS [BID], Billing.AttachmentName, Billing.BillingType, Billing.Invoice,

Billing.Description, Billing.Amount, Billing.DateCreated AS [BillingDate], Payments.ID AS [PID], Payments.Type AS PaymentType, Payments.Payment, Payments.PaymentNote,

Payments.Reason AS [BillReason], Payments.DateCreated AS [PaymentDate], Customers.ID AS [CID], COALESCE(NULLIF(Customers.Company,'') + ' - ','') + Customers.LName + ', ' +

Customers.FName AS [Name], Jobs.ID AS [JID], Jobs.JobType, Jobs.JobStatus, Jobs.JobStatusDate FROM Billing LEFT OUTER JOIN Payments ON Payments.BillingID = Billing.ID RIGHT OUTER JOIN Customers ON Customers.ID = Billing.CustomerID RIGHT OUTER JOIN Jobs ON Jobs.ID = Billing.JobID WHERE Billing.BillingType = 'Invoice' AND Billing.PaidInFull = 'No' AND Billing.Collections = 'No' AND

Billing.ChargeOff = 'No' AND Billing.Lien = 'No' AND Billing.InvoiceCanceled = 'No' AND (Billing.DateCreated >= '1/1/2014' AND Billing.DateCreated <= '8/13/14') OR (Billing.DateUpdated >=

'1/1/14' AND Billing.DateUpdated <= '8/13/14') ORDER BY Name Asc, Billing.Invoice, PID


Thanks for your help, I really appreciate it.

-Matt-


SQL JDBC connection cannot be established

$
0
0

I try to establish the connection to a SQL Server 2008 through sqljdbc4.jar file. But I always get following exception. 

Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerException (no security manager: RMI class loader disabled)
    at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:373)
    at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:163)
    at java.rmi.server.RMIClassLoader$2.loadClass(RMIClassLoader.java:620)
    at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
    at sun.rmi.server.MarshalInputStream.resolveClass(MarshalInputStream.java:197)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1574)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:225)


In jre java.policy file, I have enable all permission as below. The sqljdbc4.jar file truly is in the classpath. I have tried the lastest version of jdbc driver. It still cannot work. Please give me some suggestion, thanks!!
...
grant {
  permission java.security.AllPermission;
};

**********************************************************************

Following is my code to establish connection. It can dynamically load jdbc driver and establish connection:

/**
* Get JDBC Connection for the current database connection instance.
*/
public Connection getJDBConnection() throws Exception
{
DBDriver dbDriver = getDriver();
try
{
Class.forName(dbDriver.getClassName());
}
catch (ClassNotFoundException cnf)
{
ClassPathHacker.addFile(dbDriver.getFilePath());
Class.forName(dbDriver.getClassName());
}


try
{
Connection connection =  DriverManager.getConnection(getUrl(), getUserId(), getOrigiPassword());
System.out.println("build conenction done");
return connection;
}
catch (SQLException e)
{
// Client side does not have JDBC jar, so the SQLException thrown
// from the Oracle/SQL Server JDBC driver will be unknown on client side.
// So we need to do following conversion.
SQLException sqlExp = new SQLException(e.getMessage());
sqlExp.setStackTrace(e.getStackTrace());
throw sqlExp;
}
}

Thanks,

Alvin

Long data: Use of SQL_LEN_DATA_AT_EXEC(0) and SQL_DATA_AT_EXEC

$
0
0

Hello,

What is the use of SQL_LEN_DATA_AT_EXEC(0) and what does it mean ?

I know that when StrLen_or_IndPtr buffer pointer of SQLBindParameter is set to SQL_LEN_DATA_AT_EXEC  or SQL_DATA_AT_EXEC it means that the data for the parameter will be sent with SQLPutData.  Also SQL_LEN_DATA_AT_EXEC(length) is used when sending long data to a data source that needs to know how many bytes of long data will be sent so that it can preallocate space


But what should be the expected  behavior when we set StrLen_or_IndPtr buffer to:

     1)  SQL_LEN_DATA_AT_EXEC(0)

or  2)  SQL_DATA_AT_EXEC

Thanks

Mukesh



Unable to pass the parameter to the query while selecting the parameter for the report.

$
0
0

Hi, 

In windows form I'm trying to get the parametric report but I stuck in early stage while writing the query for the parameter.

Here in the following is the screenshot for the problem that I'm being facing.

Error while writing query

Please let me know the problem and how can I solve it?

Update users in Active Directory form SQL query update

$
0
0
I need to updatethe fields in theActive Directory 2003 usersfrom a SQL Server 2003 query. Any idea plissss???

Server Exception when using JDBC to Connect with SAP

$
0
0

Hello,

I am trying to connect to a view in an external database using JDBC. When I run the TestJDBC Tool, I get the following server exception:

com.microsoft.sqlserver.jdbc.SQLServerException: ?? ?? '<view_name>'?(?) ???????.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(Unknown Source)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(Unknown Source)
    at com.sap.ip.bi.sdk.trialarea.connector.servlet.model.JDBCModel.getColumns(JDBCModel.java:202)
    at com.sap.ip.bi.sdk.trialarea.connector.servlet.controller.Control3.doPost(Control3.java:25)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:386)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:364)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:1039)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:265)
    at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
    at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
    at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
    at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
    at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:104)
    at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:176)

The question marks really make it difficult to determine exactly what the issue is.

Is there a way to perform a trace or to determine what is going on? Our third party provider has already confirmed that the authorization they provided is correct and is working.

Thanks!

What Version of SQL Developer For Access Projects on Windows 8.1?

$
0
0
I need to Add a SQL Developer to My Windows 8.1 Pro Machine that will Work with Access projects. Which SQL Server Deveoper Version should I download. I have Access 2010.

CREATE DATABASE permission denied in database ‘master’.

$
0
0

Hi,

I have tipical situation in my database environment. i have task for deployment few object in Stage environment while running those scripts showing these error message "create database permission denied in database 'master'"

I have SA permissions in my server and environment is Sql server 2008 r2.

Please help on this.

thanks in advance

Vijay


I have problems with a DB

$
0
0

Hello I'm really frustrated because I can't enter to a Data Base, the problem is that I'm using the PC of my job and before me, other guy was in my place, and he created the DB that I need to work, the problem is, he created that DB with Windows permissions and when I want to enter to the DB I can't because my user can't access to his DB and I really need to enter.

I don't know if I'm clear in my explanation.

Thanks!

Deleted Table in SQL and DBML still remained relation !!!!

$
0
0

Hi Dear Experts

I've faced the serious problem please help me :( !

I've deleted a table from SQL database and also dbml and i created new table instead

Also in Store Procedure the new table is used
I've checked that the old table has completely removed
but when in want to excecute the solution (the SP it tells me that previous relation (Foreignkey )
is still remained ?!!!!!!) 
***THE OLD TABLE WAS IN RELATION WITH A TABLE IN SP BUT NOW IS IN RELATION WITH NEW TABLE*****

Why this error occured even i've have removed the table?????

Thanks a lot


Viewing all 4164 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>