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

Please Help me with this issue , in sql server 2012

$
0
0

when i connect to a project this message coming

TITLE: Connect to Server
------------------------------

Cannot connect to mydb.

------------------------------
ADDITIONAL INFORMATION:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)

why is this and how can i fix it?


Odd issue with SQL SELECT using MAX

$
0
0

Hi everyone.  I'm sorry to have to post on here about this, but I can't seem to figure out why this would be doing this.

I have the following SQL SELECT, which works perfectly.

SELECT Jobs.ID, Jobs.CustomerID AS [CustomerID], Jobs.ReferralID AS [ReferralID], Jobs.ReferralType, Jobs.AgentID AS [AgentID], Jobs.AdjusterID AS [AdjusterID], Jobs.EstimatorID AS [EstimatorID], Jobs.ManagerID AS [ManagerID], Jobs.JobType, COALESCE(NULLIF(Customers.Company,'') + ' - ','') + Customers.LName + ', ' + Customers.FName AS [Name], Jobs.InsuranceCompany, Jobs.DateReceived,

MAX(BillingBid.DateCreated) AS [Bid Date],

SUM(Billing.Amount) AS [Amount],

StaffEstimator.FName + ' ' + StaffEstimator.LName AS [EstimatorName], StaffManager.FName + ' ' + StaffManager.LName AS [ManagerName],

Jobs.JobStatus

FROM Jobs LEFT OUTER JOIN Customers ON Customers.ID = Jobs.CustomerID

LEFT OUTER JOIN Staff AS StaffEstimator ON StaffEstimator.ID = Jobs.EstimatorID

LEFT OUTER JOIN Staff AS StaffManager ON StaffManager.ID = Jobs.ManagerID

LEFT OUTER JOIN Billing AS BillingBid ON Jobs.ID = BillingBid.JobID AND BillingBid.BillingType = 'Bid'

LEFT OUTER JOIN Billing ON Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No'

WHERE Jobs.JobStatus = 'Active' AND (Jobs.DatePended IS NULL OR Jobs.DatePended <= '9/27/2014')

GROUP BY Jobs.ID, Jobs.CustomerID, Jobs.ReferralID, Jobs.ReferralType, Jobs.AgentID, Jobs.AdjusterID, Jobs.EstimatorID, Jobs.ManagerID, Jobs.JobType, Customers.Company, Customers.LName, Customers.FName, Jobs.InsuranceCompany, Jobs.DateReceived,  StaffEstimator.FName, StaffEstimator.LName, StaffManager.FName, StaffManager.LName, Jobs.JobStatus

ORDER BY Name Asc

Now, I have a table for Communications, and want to add to this SQL Select, the Max Date from the Communications Table that relates to this Customer... 

So I added that to the SQL Select like this:

SELECT Jobs.ID, Jobs.CustomerID AS [CustomerID], Jobs.ReferralID AS [ReferralID], Jobs.ReferralType, Jobs.AgentID AS [AgentID], Jobs.AdjusterID AS [AdjusterID], Jobs.EstimatorID AS [EstimatorID], Jobs.ManagerID AS [ManagerID], Jobs.JobType, COALESCE(NULLIF(Customers.Company,'') + ' - ','') + Customers.LName + ', ' + Customers.FName AS [Name], Jobs.InsuranceCompany, Jobs.DateReceived,

MAX(BillingBid.DateCreated) AS [Bid Date],

SUM(Billing.Amount) AS [Amount],

StaffEstimator.FName + ' ' + StaffEstimator.LName AS [EstimatorName], StaffManager.FName + ' ' + StaffManager.LName AS [ManagerName],MAX(Communications.DateCreated) AS [Last Contact], 

Jobs.JobStatus

FROM Jobs LEFT OUTER JOIN Customers ON Customers.ID = Jobs.CustomerID

LEFT OUTER JOIN Staff AS StaffEstimator ON StaffEstimator.ID = Jobs.EstimatorID

LEFT OUTER JOIN Staff AS StaffManager ON StaffManager.ID = Jobs.ManagerID

LEFT OUTER JOIN Communications ON Jobs.CustomerID = Communications.ContactID  AND Communications.ContactType = 'Customers' 

LEFT OUTER JOIN Billing AS BillingBid ON Jobs.ID = BillingBid.JobID AND BillingBid.BillingType = 'Bid'

LEFT OUTER JOIN Billing ON Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No'

WHERE Jobs.JobStatus = 'Active' AND (Jobs.DatePended IS NULL OR Jobs.DatePended <= '9/27/2014')

GROUP BY Jobs.ID, Jobs.CustomerID, Jobs.ReferralID, Jobs.ReferralType, Jobs.AgentID, Jobs.AdjusterID, Jobs.EstimatorID, Jobs.ManagerID, Jobs.JobType, Customers.Company, Customers.LName, Customers.FName, Jobs.InsuranceCompany, Jobs.DateReceived, Communications.DateCreated, StaffEstimator.FName, StaffEstimator.LName, StaffManager.FName, StaffManager.LName, Jobs.JobStatus

ORDER BY Name Asc

Unfortunately, while I am asking for the MAX Communication that matches the Left Join, it is returning ALL of the Communications that match the Left Join...

Does anyone have any idea why this might be?  No matter what I do I get the same result and I don't see anything wrong with the SQL Select...  I'm sure I'm missing something stupid...

Thanks for your help,

-Matt-

Query the data between two tables

$
0
0

Need help for query the data between two tables

Table 1: Time sheet

P.ID      P.Name EmpID HoursSpend DateTime

c12234  Test      25        4                06/12/2013

c12234  Test      25        7                06/13/2013

c12234  Test      25        8                06/15/2013

c12234  Test      5          3                06/21/2013

c12234  Test      2          5                07/15/2013

c12234  Test      25        4                07/21/2013

Table 2: cost table

EmpID  FromDate       ToDate         Rate

25         05/01/2013    06/30/2013    250

2         04/01/2013    05/31/2013      150

25         07/01/2013     09/30/2013    300 

Output

P.ID      P.Name EmpID HoursSpend DateTime       Rate   Total (HoursSond x Rate)

c12234  Test      25        4                06/12/2013    250     1000 (4*250)

c12234  Test      25        7                06/13/2013    250      1750

c12234  Test      25        8                06/15/2013    250       2000

c12234  Test      25        4              07/21/2013     300        1200

c12234  Test      2          5              07/15/2013    150           750

===========================================     

Total                           28                                                  6700

============================================

Here EmpID =2 don't have rate in the cost table on july month should be pick from last entry from cost table.

WIN XP CLIENT NOT ABLE TO ACCESS SQL 2008 ON WINDOWS SERVER 2008

$
0
0

Microsoft SQL Server Login

Conection Failed:

SQL State: '28000'

SQL Server Error: 18452

[Microsoft][ODBC SQL Server Driver][SQL Server] Login failed for user ''. The user is not associated with a trusted SQL Server connection.

I AM UNABLE TO CONNECT TO SQL INSTANCE INSTALLED ON WINDOWS SERVER 2008 FROM A NETWORKED XP CLIENT

I AM ABLE TO CONNECT VIA ADMINISTRATOR ACCOUNT ON BUT NOT ABLE TO CONNECT VIA DOMAIN OR LOCAL USER ID

I AM ABLE TO CONNECT FROM  MY LAPTOP WHICH HAS WINDOWS SERVER 2008 ALSO INSTALLED.

SQL Server 2012 upgrade causing issue with Powershell multi-value update

$
0
0
In our test environment SQL Server 2012 was upgraded to SP2 CU 1 (from the original).  The version changed from 11.0.2100 to 11.0.5532.    The powershell code for $up["SPS-Interests"].Add($Audience) which is a multi select field works for 11.0.2100 but does not work  for11.0.5532.

How to read data using SQLGetData from a block, forward-only cursor (ODBC)

$
0
0

Hi there.  I am trying to read data a small number of rows of data from either a Microsoft Access or Microsoft SQL Server (whichever is being used) as quickly as possible.  I have connected to the database using the ODBC API's and have run a select statement using a forward-only, read-only cursor.  I can use either SQLFetch or SQLExtendedFetch (with a rowset size of 1) to retrieve each successive row and then use SQLGetData to retrieve the data from each column into my local variables.  This all works fine.

My goal is to see if I can improve performance incrementally by using SQLExtendedFetch with a rowset size greater than 1 (block cursor).  However, I cannot figure out how to move to the first of the rowset returned so that I can call SQLGetData to retrieve each column.  If I were using a cursor type that was not forward-only, I would use SQLSetPos to do this.  However, using those other cursor types are slower and the whole point of the exercise is to see how fast I can read this data.  I can successfully read the data using a block forward only cursor if I bind each column to an array in advance of the call to SQLExtendedFetch.  However, that has several drawbacks and is documented to be slower for small numbers of rows.  I really want to see what kind of speed I can achieve using a block, forward-only, read-only cursor using SQLGetData to get each column.

Here is the test stub that I created:

        ' Create a SELECT statement to retrieve the entire collection.
        selectString = "SELECT [Year] FROM REAssessmentRolls"

        ' Create a result set using the existing read/write connection.  The read/write connection is used rather than
        ' the read-only connection because it will reflect the most recent changes made to the database by this running
        ' instance of the application without having to call RefreshReadCache.
        If (clsODBCDatabase.HandleDbcError(SQLAllocStmt(gDatabase.ReadWriteDbc, selectStmt), gDatabase.ReadWriteDbc, errorBoxTitle) <> enumODBCSQLAPIResult.SQL_SUCCESS) Then
            GoTo LoadExit
        End If
        Call clsODBCDatabase.HandleStmtError(SQLSetStmtOption(selectStmt, SQL_CONCURRENCY, SQL_CONCUR_READ_ONLY), selectStmt, errorBoxTitle)
        Call clsODBCDatabase.HandleStmtError(SQLSetStmtOption(selectStmt, SQL_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY), selectStmt, errorBoxTitle)
        Call clsODBCDatabase.HandleStmtError(SQLSetStmtOption(selectStmt, SQL_ROWSET_SIZE, MAX_ROWSET_SIZE), selectStmt, errorBoxTitle)
        If (clsODBCDatabase.HandleStmtError(SQLExecDirect(selectStmt, selectString, Len(selectString)), selectStmt, errorBoxTitle) <> enumODBCSQLAPIResult.SQL_SUCCESS) Then
            GoTo LoadExit
        End If

        ' Cursor through result set.  Each time we fetch data we get a SET of rows.
        sqlResult = clsODBCDatabase.HandleStmtError(SQLExtendedFetch(selectStmt, SQL_FETCH_NEXT, 0, rowsFetched, rowStatus(0)), selectStmt, errorBoxTitle)
        Do While (sqlResult = enumODBCSQLAPIResult.SQL_SUCCESS)

            ' Read all rows in the row set
            For row = 1 To rowsFetched
                If rowStatus(row - 1) = SQL_ROW_SUCCESS Then
                    sqlResult = clsODBCDatabase.HandleStmtError(SQLSetPos(selectStmt, row, SQL_POSITION, SQL_LOCK_NO_CHANGE), selectStmt, errorBoxTitle)
                    Call clsODBCDatabase.SQLGetShortField(selectStmt, 1, assessmentRollYear(row - 1))
                    Console.WriteLine(assessmentRollYear(row - 1).ToString)
                End If
            Next

            ' If the rowset we just retrieved contains the maximum number of rows allowed, there could be more data.
            If rowsFetched = MAX_ROWSET_SIZE Then ' there could be more data
                sqlResult = clsODBCDatabase.HandleStmtError(SQLExtendedFetch(selectStmt, SQL_FETCH_NEXT, 0, rowsFetched, rowStatus(0)), selectStmt, errorBoxTitle)
            Else
                Exit Do ' no more rowsets
            End If

        Loop  ' Do While (sqlResult = enumODBCSQLAPIResult.SQL_SUCCESS)

The test fails on the call to SQLSetPos.  The error message I get is "Invalid cursor position; no keyset defined".  I have tried passing SET_POSITION and also SET_REFRESH.  Same error.  There has to be a way to do this!

Thank you for your help!


Thank You! - Andy

SqlFileStream error: The network path was not found

$
0
0

I created a FileStream enabled table in a SQL2008 database, and populated some rows into it, from a SQL2000 table storing image. It's fine.

Then I wrote a WPF application in C#, trying to access the filestream data as below code snippet:

      SqlConnection sqlConn = null;
      SqlTransaction sqlTran = null;
      try
      {
// ids_static_imagesTableAdapter was defined by SQL SELECT statement:
// SELECT TOP (@x) image_name, image, image.PathName() AS image_path FROM dbo.ids_static_images
ids_static_imagesTableAdapter imgTa = new ids_static_imagesTableAdapter(); sqlConn = imgTa.Connection; sqlConn.Open(); idsxi2011imageDataSet.ids_static_imagesDataTable imgDt = imgTa.GetData(10); sqlTran = sqlConn.BeginTransaction(); SqlCommand cmdGetFsTxCtx = sqlConn.CreateCommand(); cmdGetFsTxCtx.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()"; cmdGetFsTxCtx.Transaction = sqlTran; byte[] fileStreamTxCtx = (byte[])cmdGetFsTxCtx.ExecuteScalar(); foreach (idsxi2011imageDataSet.ids_static_imagesRow imgRow in imgDt) { SqlFileStream imgSqlFileStream = new SqlFileStream(imgRow.image_path, fileStreamTxCtx, FileAccess.Read); Add(new ImageFile(imgRow.image_path, imgRow.image_name, imgSqlFileStream)); } sqlTran.Commit(); } finally { if (sqlConn != null && sqlConn.State == ConnectionState.Open) { sqlConn.Close(); } }

The SqlFileStream constructor throws error, states 'The network path was not found'.

FYR, when I run the following SQL statement in SSMS:
SELECT TOP 1 image.PathName() AS image_path FROM dbo.ids_static_images
result as below:
\\XISERVER\MSSQLSERVER\v1\idsxi2011image\dbo\ids_static_images\image\3B121497-07E6-4568-9DDC-EFEAA57BE6AA

Any idea?

The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction.

$
0
0

We have a test db, a staging db and a live db.  I have a stored procedure that runs fine on test and staging, but throws the following error on live. 

 

The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction.

 

The stored procedure uses linked servers and a transaction.

We're using the following transaction code in the stored procedure

BEGIN

BEGINTRANSACTION

BEGINTRY

---

procedure stuff here

---

COMMITTRANSACTION

ENDTRY

BEGINCATCH

DECLARE @ErrorSeverity INT, @ErrorNumber INT, @ErrorMessage NVARCHAR(4000), @ErrorState INT

SET @ErrorSeverity = ERROR_SEVERITY()

SET @ErrorNumber = ERROR_NUMBER()

SET @ErrorMessage = ERROR_MESSAGE()

SET @ErrorState = ERROR_STATE()

IF @ErrorState = 0

SET @ErrorState = 1

RAISERROR('ERROR OCCURED:%d', @ErrorSeverity, @ErrorState, @ErrorNumber)

IF XACT_STATE()< 0

ROLLBACKTRANSACTION

ENDCATCH

 

END

 

I found the following link which seems to be the problem we're experiencing

http://support.microsoft.com/kb/937517

 

The link includes a workaround which is the following:

"To prevent the SQLNCLI provider from sending an attention signal to the server, use the SQLNCLI provider to consume fully any rowsets that the OLE DB consumer creates. "
 
 
How do I use the SQLNCLI provider to fully consume any rowsets?

How to execute sql scripts from Powershell across multiple databases

$
0
0

Re: How to execute sql scripts from Powershell across multiple databases

I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.

Hadoop ODBC linked server error: Specified driver could not be loaded due to system error 182

$
0
0

Hi,

I am trying to connect to a Hadoop server through a linked server in SQL Server. I downloaded and installed the Microsoft Hive ODBC driver - HiveODBC64.msi. But while I am trying to create the Linked server using this ODBC driver I am getting below error.

" Specified driver could not be loaded due to system error 182 (Microsoft Hive ODBC driver, D:\....\HiveODBC64.dll). (Microsoft SQL Server, Error: 7303)"

When I tested it locally and in another server, it is working properly. I am getting this error only in this server. looks like a dll error. But cannot identify where/what is the error. Could someone help me fix this issue.

Server info:

OS Name: Microsoft Windows Server 2008 R2 Enterprise Version 6.1.7601 Service Pack 1 Build 7601

SQL SERVER: Microsoft SQL Server 2008 R2(SP1)

Application call to ODBC SQLSetEnvAttr function throw HY011 exception

$
0
0

Hi All,

      I try to use odbc driver manager in my .Net Application.first My .Net runtime is 3.5, odbc function calls(unmanaged functions are  imported to .Net application by dllimport attribute)can work well.but when .Net runtime is upgraded to 4.0,SetEnvAttr function calls

return SQL-ERROR and I call SQLGetDiagRec function  get this error information:Operation invalid at this time.sqlstate value is HY011.

below is my code fragment:

     
  [DllImport("odbc32.dll")]
        extern static short SQLSetEnvAttr(
            IntPtr envHandle,
            ushort attribute,
            IntPtr attrValue,
            int stringLength);

        [DllImport("odbc32.dll")]
        extern static short SQLAllocHandle(
            ushort HandleType,
            int InputHandle,
            out IntPtr OutputHandle);
try
            {
                rc = SQLAllocHandle(SQL_HANDLE_ENV, 0, out sql_env_handle);
                if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
                {
                    throw new Exception("SQLAllocHandle: failed to allocate SQL_HANDLE_ENV");
                }
                rc = SQLSetEnvAttr(sql_env_handle, SQL_ATTR_ODBC_VERSION, (IntPtr)SQL_OV_ODBC3, 0);
                //if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
                //{
                //    throw new Exception("SQLSetEnvAttr: failed to set SQL_ATTR_ODBC_VERSION");
                //}
                if((rc == SQL_SUCCESS_WITH_INFO)||(rc == SQL_ERROR))
                {
                    short i=1;
                    short rc2;
                    StringBuilder sqlstate=new StringBuilder();
                    int NativeErrorPtr=0;
                    StringBuilder MessageText=new StringBuilder();
                    short BufferLength=256;
                    short TextLengthPtr=0;
                    while ((rc2 = SQLGetDiagRec((short)SQL_HANDLE_ENV,sql_env_handle,i,sqlstate,
                        ref NativeErrorPtr,MessageText,BufferLength,ref TextLengthPtr))!= SQL_NO_DATA)
                        {
                        i++;
                    }
                }

my operation system is win7 64bit. Could someone help me? thanks

Linked server accesss

$
0
0

Hi, I have 2 server  2014.

Created a linked server from server1 to server2, but in the linked server catalog I am not able to find all the databases. some of them are missing.

it is a permission issue , but i am not able to figure it out.

Static server-side cursor does not return a valid record count when using common table expressions

$
0
0

According to the ADO documentation, static cursors are always supposed to return the actual number of rows (emphasis mine):

The RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.

However, this is apparently untrue when using the SQLOLEDB provider and an SQL statement that includes a common table expression. Here's a minimal reproducible VBA example:

Const sql1 = "SELECT myField FROM myTable"
Const sql2 = "WITH mycte AS (SELECT myField FROM myTable) SELECT myField FROM myTable"

Dim cn As New ADODB.Connection
cn.Open "Provider=SQLOLEDB;Server=myServer;Initial Catalog=myDatabase;Integrated Security=SSPI"

Dim rs As New ADODB.Recordset
rs.CursorLocation = adUseServer

rs.Open sql1, cn, adOpenStatic, adLockReadOnly, adCmdText
Debug.Print rs.RecordCount      ' Yields 156 '
rs.Close

rs.Open sql2, cn, adOpenStatic, adLockReadOnly, adCmdText
Debug.Print rs.RecordCount      ' Yields -1; should be 156 '
rs.Close

cn.Close

Is this a known issue?

I am aware that I can work around this issue by using a client-side instead of a (default) server-side cursor, but I'd rather not do that to avoid introducing regressions in our legacy code.

(PS: I know that my example code does not access mycte. The declaration suffices to reproduce the problem: It is not necessary to actually use the CTE.)

Use DISTINCT with two fields to return one record

$
0
0

I am using OleDB with a SELECT DISTINCT query that is used in C# code to populate a DataGridViewComboBox.  The queried table has two fields: ID and Description. The ID field values are unique. Descriptions may be duplicated. The DataSource of my DataGridViewComboBox is ListBoxItems which is a ListBox that is populated from a table. The ValueMember is ID and the DisplayMember is Description.  A sample table might look like this:

ID    Description

 1     Blue

 2     Blue

 3     Red

 4     Blue

I want my query to return two records; one for the Red description and only one for the Blue description.  I don't care which Blue description it returns, but I do need the corresponding ID for the selected Blue record and the ID value for the Red record.  Using SELECT DISTINCT ID, Description FROM... would give me four records instead of two.  How can I return only two records in this scenario?


Rob E.


Buk insert Prblem

$
0
0

BULK Insert UploadNew from 'D:\NewData.xlsx' with (Fieldterminator = ',' ,RowTerminator ='\n')

I have use this query for bulk insert from excel file 

but I have faced the problem that, inserts in only one row .

new record start in new row in excel but rowTerminator didn't work, I am working on sql server 2008 R2

Plz give replay quicky


Log for database 'tempdb' is not available

$
0
0
Can someone please advice me why once in a while we get the below error message on our SQL server..

The log for database 'tempdb' is not available. Check the event log for related error messages. Resolve any errors and restart the database. (.Net SqlClient Data Provider)

I know that by restarting the SQL services fixes this problem. But i would like to understand why this happens and how it can be avoided in future...!

Thanks.

Deleting a data that is in a (view) on a stored proc

$
0
0

HI, I'm trying to delete data that is in a (view) on a stored proc

.......sp_DeleteFoodType – Delete a specific food type and all dependent/child records.  However, only delete the type if it is contained in the vw_ExpiredFoodDetails view.....THIS IS THE QUESTION I  AM HAVING PROBLEMS WITH>>>>

 

Inserting data from another database using web form

$
0
0

Hello,

I'm not sure if this is the correct forum.  This is sort of between SQL Server and ASP.NET.

I have a web form that is populated with data from user entries.  When saved, the record is inserted into a UserData table from user database.  However, some fields need to be populated from another database, based on values entered by the user on some fields (textboxes).

How do I "pull out" those fields/column values from the other database so I can include them in my insert statement?  The insert statement is a stored procedure in SQL Server 2012.

My VB code snippet to insert into SQL Server is as follows:

'Open a connection to the database
If cn.State == Connection.Closed Then cn.Open()

Dim cmd As SqlCommand = New SqlCommand("InsertMyData", cn)  '  example: Database: DB1 and table: MyUserData
cmd.CommandType = CommandType.StoredProcedure

'Add parameters from web form
cmd.Parameters.AddWithValue("@crop1_Association", lblFRate1.Text)
cmd.Parameters.AddWithValue("@cropDesc", Crop1Desc.Text)

'The following is the column I need to fill with data from the other database (say, DB2) and table (say, MGT2)

cmd.Parameters.AddWithValue("@crop1MgtDate", "")         

   ...

'I'm skipping more columns for insertion for brevity's sake.

cmd.ExecuteNonQuery()

Appreciate any help.


Marilyn Gambone

How to connect with vb.net to SQL Server 2008 R2 SOAP ENDPOINT using BASIC authentification

$
0
0

Hi,

I use these endpoints all the time with NTLM authentication and windows clients, but now I need one with BASIC authentication... and I can't get past the "The underlying connection was closed. An unexpected error occurred on a send." error.

I have a SOAP ENDPOINT created on the server, like this:

CREATE ENDPOINT MY_SERVICE
  STATE=STARTED
AS HTTP
(
  PATH='/MY_SERVICE', AUTHENTICATION=(BASIC), PORTS=(SSL), SSL_PORT=443, SITE = '*',  COMPRESSION = DISABLED
)
FOR SOAP
(
   -- ADMIN
   WEBMETHOD 'getServerDateTime' (NAME='MYDB.ADMIN.getServerDateTime', SCHEMA=STANDARD, FORMAT=ROWSETS_ONLY),
   -- Lots of WEBMETHODs here...
   -- END
   BATCHES=DISABLED, WSDL=DEFAULT, DATABASE='MYDB', NAMESPACE=DEFAULT, LOGIN_TYPE=MIXED
)
GO
GRANT CONNECT ON ENDPOINT:: MYSERVICE TO [MYDB\LocalUserOnServer]

The local user has the following attributes and getServerDateTime stored procedure is in the Admin Schema, with the following def:

exec sp_grantLogin    'MYDB\LocalUserOnServer'
exec sp_grantdbaccess    'MYDB\LocalUserOnServer'
exec sp_addrole 'My_Users'
exec sp_addrolemember My_Users, [MYDB\LocalUserOnServer]
CREATE SCHEMA ADMIN AUTHORIZATION dbo
    GRANT EXECUTE TO My_Users

In the VB code I add the webservice to the project and give it the name MYDB, and VS makes the type for it.

This class wraps the task of calling the service methods/stored procedures:

Imports System.Net
Public Class ServiceAgent
' **-*-*-**-*-*-**-*-*-**-*-*-**-*-*-**-*-*-**
Public Function VerifyUserAccess(ByRef err As String) As Boolean
	err = ""
	Try
		Using obj As MYDB.MY_SERVICE = GetServiceObject()
			Return (ServiceAgentHelper.DS_String(obj.getServerDateTime()) <> "")
		End Using
	Catch ex As Exception
		err = ex.Message
		Return False
	End Try
End Function
Private Shared Function GetServiceObject() As MYDB.MY_SERVICE
	Dim myCache As New CredentialCache()
	myCache.Add(New Uri("https://MYDB/MY_SERVICE"), "Basic", New NetworkCredential("MYDB\LocalUserOnServer", "CrazyHardToCrackPassword"))
	Return New MYDB.MY_SERVICE() With {.Credentials = myCache, .Timeout = 60000, _
	                                           .Url = "https://MYDB/MY_SERVICE", .PreAuthenticate = True}
    End Function
End Class

When I call VerifyUserAccess() I get the "The underlying connection was closed. An unexpected error occurred on a send." error.  

What am I missing???

Thanks!

Get values from different Tables based on value in SELECT

$
0
0

I don't know if my Title makes much sense...  So I'll describe better here.

I have a SELECT that pulls data from a Customers Table.  The issue I am having is that some data may be in one of 2 tables dependent on a value in the SELECT.  So, the data may look like this:

ID, CustomerName, Address, ReferralSource, ReferralType

ReferralType may refer to one of 2 tables.  So I want to get the appropriate ReferralSource based on the ReferralType.  I'm already pulling a lot of data into this SELECT, so I was thinking I may need to do this as a Subquery, which supports If Statements it seems, but I wasn't sure how to really do this.

Any help is greatly appreciated...

Thanks

Viewing all 4164 articles
Browse latest View live


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