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

Is there a way to find out if SqlDataReader has multiple results?

$
0
0

I checked some MSDN documentation and also looked through a few blogs or StackOverflow questions, but do not see the answer to my question.

I know that we can use NextResult() method to read next result if it exists.

This is my current code

 StringBuilder result = new StringBuilder(returnMessage);

               while (sqlDataReader.NextResult())
               {
                  result.AppendFormat("\r\n{0}", GetFormattedReturn(sqlDataReader, returnType, out recordCount));
               }
               returnMessage = result.ToString();

However, if there is only a single result set, I do not need to instantiate a new StringBuilder instance.

So, I am wondering if there is some other way to find out if SqlDataReader has multiple results?

If not, do you think I may be better using just string concatenation then? I believe we normally don't have more than 3 results (and in 99% of cases we only have 1 result). I don't know if it's better to just not worry about string memory problems and just concatenate strings together without using a StringBuilder.

So, that's my question.

Thanks in advance.


For every expert, there is an equal and opposite expert. - Becker's Law


My blog


My TechNet articles


SQL Database save in network folder

$
0
0
I have SQL server 2008 R2 i have one query i want to save .bak file network folder. please help how it possible.

huz

SQL SERVER error during insert

$
0
0

Hi,

I am facing with multiple problems from creation of the table to inserting data into it. I am using SQLSERVER 9.0

1) The issue while creating the table, I need two dates(timestamp) to be created, The error thrown is :

Msg 2738, Level 16, State 2, Line 1
A table can only have one timestamp column. Because table 'table_name' already has one, the column 'CHANGE_DATE' cannot be added.

2)  I am resolving the above error by using only one timestamp field and making other as varchar for executing the code. The issue is with insert command. 

insert into schema.dbo.table_name

select * from schema.dbo.source_table;

gives me an error.

3) I tried to resolve this error by using the format of 

insert into schema.dbo.table_name values (a,b,c)

select a,b,c from schema.dbo.source_table;

But this is followed by the error

Msg 128, Level 15, State 1, Line 2
The name "BRAND_ID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

All these problems go away with using the statement 

select * into schema.dbo.table_name from schema.dbo.source_table;

Why is the traditional insert select causing problems in SQL SERVER 9.0?

no output

$
0
0
hi masters...i have this query in my application. I am not getting anyoutput. plz
REGSQL = "select '<a href=""filetrack.aspx?fname='||chg_filename||'||"">'||chg_filename||'</a>' as ""File No"",file_subject as ""File Subject"",(select RECEIPT_DATE from FILETRANS where filemaster.file_serial_no = FILETRANS.file_serial and filemaster.file_year=FILETRANS.file_year and filetrans.RECEIPT_DATE between trunc(sysdate-6)+(15/24) and least( trunc(sysdate)+(15/24), sysdate) and rownum=1) as ""Received Date"",(select department_name from departments where department_code=filemaster.department_code and rownum=1) as ""Dept"",(select section_name from sections where section_cd=filemaster.section_code and rownum=1 and dept_cd=filemaster.department_code) as ""Section"" from filemaster " 

tell me where is the problem.

thanks and regard love4csharp

Unable to access Linked Server from Client PC

$
0
0

Hi guys  

I have an issue when trying to connect to linked servers from a client PC.

The linked servers connection in question works when it gets accessed from the server but when a Client PC tries to connect to it then they receive the following error:


An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

------------------------------

Cannot initialize the data source object of OLE DB provider "MSOLAP" for linked server "SRV2".

OLE DB provider "MSOLAP" for linked server "SRV2" returned message "An error was encountered in the transport layer.".

OLE DB provider "MSOLAP" for linked server "SRV2" returned message "The peer prematurely closed the connection.". (Microsoft SQL Server, Error: 7303)

------------------------------

Anyone else seen this issue or know how to resolve this?

Thanks

OLE DB Provider for ODBC limitations when connecting to MySQL?

$
0
0

Hi,

I have setup a Linked Server using OLE DB Provider for ODBC to a MySQL 5.2 (?) instance.  I can select from 230 of the 231 tables through the link, but one table fails a query if I include a column which is varchar(32000).   If I leave out that column, the query works. 

So I was wondering if this is a limitation of ODBC, or perhaps this is a configuration issue?  I can live without  the data, but it would be nice to be able to retrieve this.

OLE DB provider "MSDASQL" for linked server "MYSQLECC" returned message "Requested conversion is not supported.".

Msg 7341, Level 16, State 2, Line 1

Cannot get the current row value of column "[MYSQLECC]...[sql_per_category].sql_string" from OLE DB provider "MSDASQL" for linked server "MYSQLECC".

Thanks,

Mike

performance on Query

$
0
0

I created a view with 10 tables. one of the table has name (nvarchar(200)) , alias name, and notes (nvarchar(max)). when my view select the above 3 field, the reads of query hits 10 time more, if I select other column UID, integer column of the same table, the reads of the query is not increase. why the reads are increased 10 time when my query select the column nvarchar data type.

I tried with varchar also. I faced the same problem.


Developer

Connecting to SQL on a domain from a workgroup

$
0
0

I have set up a new installation of SQLExpress 2012 on a Windows Essentials 2012 Server. <o:p></o:p>

I have set it up with mixed authentication, and whilst testing I am using the sa user. <o:p></o:p>

I have a small office network, which I have been running as a workgroup (15 or so PCs and printers).<o:p></o:p>

Eventually I will migrate these to a domain, but it will take a bit of time for me to do this. In the interim I need connect to the SQL server from the workgroup.<o:p></o:p>

I have one PC which is joined to the domain, when I login to the domain, I can connect vie Management Studio. However when I login, as the local user, I get the error<o:p></o:p>

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: 1326)<o:p></o:p>

Interestingly, I can find the server when I browse for servers. <o:p></o:p>

So my question, is how I can connect to the domain SQL server from outside the domain (in this case a workgroup, not another domain) please? <o:p></o:p>


Paddy


How to rollback changes in SQL Server 2005

$
0
0

I have updated data on production SQL Server 2005 database by accident. I executed the update statement from management studio.

Is there any way to rollback those transactions?

Microsoft.ACE.OLEBD.12.0

$
0
0

With 64 bit SQL 2008 on Server 2008 I read .dbf table with a long file name using:

SELECT * FROM OPENROWSET(

'Microsoft.ACE.OLEDB.12.0'

,'dbase IV;Database=D:\WebTest\ShapeFiles'

,'SELECT * FROM [sppobs~4]')

because I get an error

"The Microsoft Access database engine could not find the object ...

when I use the entire name in the FROM clause.  Is there a syntax allowing me to specify a table name longer than 8 character length?

Linked Server results in: Msg 208, Level 16, State 1, Line 1 Invalid object name [Table Name]

$
0
0

Hello All,

Currently we are moving all our servers to a datacenter. We have been provided with 5 new SQL servers and I need to order the new servers. I have Administrator rights to do this

I need to create a Linked server on a Microsoft SQL Server Standard Edition 64 bit 2008 to another Microsoft SQL Server Standard Edition 64 bit 2008.

I Created a linked server from server1 to server2 and this worked as expected.

(

I Used  SSMS and simply klikt "New Linked Server..." I inserted the correct Linked Server and selected Server type SQL Server. In Security I selected Connections will be made using this security context: And inserted a SA user and Password here. 

After this I wanted to create a similar linked server from Server2 to Server1, however after following the steps above I received an error. (Linked server already exists) After searching for a couple of solutions I found that in running this query:

SELECT * FROM sys.servers

The server indeed was in here. (Server_Id 0) With some different values then the first linked server from server1 to server2. For example the column is_linked was 0 and the is_remote_login_enabled=1.

I dropped this (linked) server with the stored procedure to drop linked servers. After this I created the linked server as above and the linked server from server2 tot server1 was created. 

When clikking through the linked server the databases this linked server should have rights to where all visible, however when Selecting data in a Query the following error message is supplied:

Msg 208, Level 16, State 1, Line 1
Invalid object name '[Database].DBO.[Table]'

I Dropped and created the linked server serveral times, and also supplied the user which is used in the linked server with Sysadmin rights, however this all did not work. 

Hopefully somebody can help me with this problem! I have been working a while on this problem and the linked server needs to work for my reports.

Kind Regards,

Tommax


How connecting SQL Server instance to a SAP ERP installation - help

$
0
0

Hi,

I need to know how I can read data from a SAP ERP installation to a SQL Server instance.

Does it exist any data providers? Are free?

Thanks

How to handle 'DROP TABLE' executed using ICommand::Execute of OLEDB in c++ ?

$
0
0

Hi,

I am using the below OLEDB program to connect with SQL server 2012 and execute commands on the database.

All the queries except DROP TABLE works fine. When DROP TABLE command is executed the below program aborts while the ICommandText::Execute is executed.

Please provide me suggestions to handle the 'DROP TABLE' command. Any way to find that the ICommandText::Execute has executed the 'DROP' command ? Any properties to be set?

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <oledb.h>
#include <atlbase.h>
#include <stddef.h>
#include <oledberr.h>
#include <sqlncli.h>

void main(int argc, char* argv[])
{    
                 IUnknown *    pIUnknown ;
                 BOOL *        pbValue = FALSE;
                 CLSID        clsid;
                 HRESULT        hr;
                  IDBInitialize *        pIDBInitialize ;
                  IDBProperties*        pIDBProperties ;
                  IMultipleResults*   pIMultipleResults;
                  IRowset*            pIRowset;
                  IUnknown *     g_pISession;
                  hr = CoInitialize(NULL);

                char *pSQLNCLI_progidName = NULL;
                pSQLNCLI_progidName = strdup("SQLNCLI10");
                int lenA = lstrlenA(pSQLNCLI_progidName);
                int lenW = 0;
                BSTR sqlncli_progidW = NULL;
                
                lenW = ::MultiByteToWideChar(CP_ACP, 0, pSQLNCLI_progidName, lenA, 0, 0);
                if (lenW > 0)
                {
                                // Check whether conversion was successful
                                sqlncli_progidW = ::SysAllocStringLen(0, lenW);
                                ::MultiByteToWideChar(CP_ACP, 0, pSQLNCLI_progidName, lenA, sqlncli_progidW, lenW);
                }
                else
                {
                                fprintf(stderr," *** ERROR *** progid conversion failure from char to Wchar \n");
                }

                // retrieve the clsid from register by program name, SQLNCLI11(2012) or SQLNCLI10(2008)
                CLSID   clsidSQLNCLI = CLSID_SQLNCLI;
                hr = CLSIDFromProgID(sqlncli_progidW,  &clsidSQLNCLI);
                
                hr = CoCreateInstance( clsidSQLNCLI,NULL,CLSCTX_INPROC_SERVER,IID_IDBInitialize,(void **) &pIDBInitialize);
                fprintf(stderr, "Instance created \n" );
                const ULONG nProps = 4;
                DBPROP InitProperties[nProps];
               DBPROPSET rgInitPropSet[1];

                  for (ULONG i = 0; i < nProps; i++)
                  {
                                  VariantInit(&InitProperties[i].vValue);
                                  InitProperties[i].dwOptions = DBPROPOPTIONS_REQUIRED;
                                  InitProperties[i].colid = DB_NULLID;
                  }

                InitProperties[0].dwPropertyID                                = DBPROP_INIT_DATASOURCE;
                InitProperties[0].vValue.vt                                          = VT_BSTR;
                InitProperties[0].vValue.bstrVal               = SysAllocString(OLESTR("MACHINE\\MSSQLSERVER11"));
                InitProperties[0].dwOptions                                       = DBPROPOPTIONS_REQUIRED;
                InitProperties[0].colid                                                    = DB_NULLID;
                InitProperties[0].dwStatus                                          = DBPROPSTATUS_OK;
                
                //Specify database name.
                InitProperties[1].dwPropertyID                                = DBPROP_INIT_CATALOG;
                InitProperties[1].vValue.vt                                          = VT_BSTR;
                InitProperties[1].vValue.bstrVal               = SysAllocString(OLESTR("TEST"));
                InitProperties[1].dwOptions                                       = DBPROPOPTIONS_REQUIRED;
                InitProperties[1].colid                                                    = DB_NULLID;

                //Specify user name (login).
                InitProperties[2].dwPropertyID                                = DBPROP_AUTH_USERID;
                InitProperties[2].vValue.vt                                          = VT_BSTR;
                InitProperties[2].vValue.bstrVal               = SysAllocString(OLESTR("sa"));
                InitProperties[2].dwOptions                                       = DBPROPOPTIONS_REQUIRED;
                InitProperties[2].colid                                                    = DB_NULLID;
                
                //Specify password.
                InitProperties[3].dwPropertyID                                = DBPROP_AUTH_PASSWORD;
                InitProperties[3].vValue.vt                                          = VT_BSTR;
                InitProperties[3].vValue.bstrVal               = SysAllocString(OLESTR("Password"));
                InitProperties[3].dwOptions                                       = DBPROPOPTIONS_REQUIRED;
                InitProperties[3].colid                                                    = DB_NULLID;
                
                //Assign the property structures to the property set.
                 rgInitPropSet[0].guidPropertySet = DBPROPSET_DBINIT;
                 rgInitPropSet[0].cProperties = nProps;
                 rgInitPropSet[0].rgProperties = InitProperties;
                
                  hr = pIDBInitialize->QueryInterface(IID_IDBProperties, (void **)&pIDBProperties);
                  hr = pIDBProperties->SetProperties(1, rgInitPropSet);
                  pIDBProperties->Release();

                 ULONG i; //Infosys:64-bit change:i declared out of for loop as ULONG
                 for( i=0; i<nProps; i++ )
                 {
                                  if (InitProperties[ i ].vValue.vt == VT_BSTR)
                                  SysFreeString( InitProperties[ i ].vValue.bstrVal );
                 }

                 hr = pIDBInitialize->Initialize();
                  if (FAILED(hr)) {
                                fprintf(stderr,"initialize failed %X\n", hr );
                                return;
                }
                //These variables are for Command creation.
                 IDBCreateSession*       pIDBCreateSession;
                 IDBCreateCommand*       pIDBCreateCommand;
                
                 ICommandText*           pICommandText;
                 DBROWCOUNT                    cRowsAffected;

                 //Get the DB Session object.
                  hr = pIDBInitialize->QueryInterface(IID_IDBCreateSession,(void**)&pIDBCreateSession);
                  if (FAILED(hr)){
                                fprintf(stderr,"Query:create session failed \n" );
                                    return;
}
    
//Create the session, and get an interface for command creation.
                hr = pIDBCreateSession->CreateSession(NULL,IID_IOpenRowset, (IUnknown**)&g_pISession);
                
                 if (FAILED(hr)){
                                fprintf(stderr,"create session failed \n" );
                  return;
}

                hr = g_pISession->QueryInterface(IID_IDBCreateCommand,  (void**)&pIDBCreateCommand);
                  //Create the command object.

                  hr = pIDBCreateCommand->CreateCommand(NULL, IID_ICommandText,(IUnknown**)&pICommandText);
                  pIDBCreateCommand->Release();
                  if (FAILED(hr))
                                 return;

                 // hr = pICommandText->SetCommandText(DBGUID_DBSQL, L"select * from TestTable");
                  //hr = pICommandText->SetCommandText(DBGUID_DBSQL, L"INSERT INTO TestTable(ID) VALUES ('2377434')");
    //hr = pICommandText->SetCommandText(DBGUID_DBSQL, L"DELETE FROM TestTable WHERE ID = '2377434'");
    hr = pICommandText->SetCommandText(DBGUID_DBSQL, L"DROP TABLE TestTable");
   
                 //Execute the command.
                hr = pICommandText->Execute( NULL,IID_IRowset,NULL,&cRowsAffected,(IUnknown **) &pIRowset );
                
                if(hr != S_OK)
                 {
                                fprintf(stderr," Error - execute  \n");
                }
                else{
                                  if (cRowsAffected > 0)
                                  {
                                          fprintf(stderr," Updated rows = %d  \n" , cRowsAffected);
                                           return;
                                  }
                }

// Retrieve records.
                HROW hRow = NULL;
                HROW *rghRow = &hRow;
                DBCOUNTITEM cRowsObtained = 0;
                hr = pIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &rghRow);
                fprintf(stderr, " Selected Rows = %d  \n" , cRowsObtained);
return;

}

Thanks in advance

JDBC 3/4 loginTimeout property not properly implemented. 'Hung' threads as result.

$
0
0

The JDBC loginTimeout property is not working correctly. Currently, it will only time out on not getting a socket connection to the database server. However, when a socket connection is established, but the log in procedure fails technically (not receiving either access confirmation or denial) , this results in a 'hung' connection/thread.

This happens most often with the recent forced SSL authentication on SQL 2008 / JDBC 3 driver.

Even if this thread is stop()ped, the resulting connection stub will obstruct the Java finalizer, and break finalizing / GC.

This can be easily observed in the current Java 1.6.0_29 version, where the SSL communication in Java is bugged, and makes this problem 100% reproduceable. However, even with other Java versions this problem is seen intermittently.

The JDBC driver SHOULD timeout these failed connections but DOESN'T. Regardless of  underlying protocol problems, it should throw an exception after the loginTimeout period. Make the timeout period not only include getting a socket, but THE ENTIRE LOGIN procedure, up until the connection is ready to receive queries.








print select statement

$
0
0

hi

i use cursor for output report but don't know how to set up it for Print

problematic part is 49-54 line, when select is displayed in Grid and not as text and every line has own head. i need to how can i do it. thx

SET NOCOUNT ON;

DECLARE 
@DEN as varchar(15),
@message as nvarchar(200),
@dbkey as varchar (5),
@eod as varchar (20),
@datum as varchar (20),
@nazov as varchar (20),
@pokladna as varchar (20),
@suma as varchar (20)


PRINT '-------------------------Report Uverov-----------------------';

DECLARE hlavicka_cursor CURSOR FOR 
select distinct DATUM 
from dbo.tab_loans_cz;

OPEN hlavicka_cursor

FETCH NEXT FROM hlavicka_cursor 
INTO @DEN

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT ' '
    select @message = 'Uvery za den: ' + @DEN
    PRINT @message 
    PRINT '--------------------------'

    -- Declare an inner cursor based   
    -- on @DEN from the outer cursor.

    DECLARE telicko_cursor CURSOR FOR 
    SELECT dbkey,eod,datum,nazov,pokladna,suma
    FROM dbo.tab_loans_cz
    WHERE DATUM=@DEN  -- Variable value from the outer cursor

    OPEN telicko_cursor
    FETCH NEXT FROM telicko_cursor INTO @dbkey,@eod,@datum,@nazov,@pokladna,@suma

    IF @@FETCH_STATUS <> 0 
        PRINT '         <<None>>'     

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SELECT @message = 'select QUOTENAME(EOD),QUOTENAME(datum) from 
        dbo.tab_loans_cz a where dbkey='+@dbkey
        exec (@message)
        PRINT @message 
        FETCH NEXT FROM telicko_cursor INTO @dbkey,@eod,@datum,@nazov,@pokladna,@suma
        END

    CLOSE telicko_cursor
    DEALLOCATE telicko_cursor
        -- Get the next vendor.
    FETCH NEXT FROM hlavicka_cursor 
    INTO @DEN
END 
CLOSE hlavicka_cursor;
DEALLOCATE hlavicka_cursor;














Calling powershell function from TSQL

$
0
0

I have a .ps1 file called Test.ps1.

A function in it called TestFunction

How can I access this function from TSQL?

The following command works for running the .ps1 file, but adding the function to it doesn't hit the function.

EXEC xp_cmdshell ' powershell . C:\Desktop\Test.ps1'

I refered to this article which talks about gettin the command correct in command prompt, but coiuldn't make it to work.

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/672ddc58-c222-45a1-8d7d-1e96a630481c/execute-powershell-function-within-tsql

I also want to pass parameters in the function call. Please suggest.


What value should i put into the SQLBindParameter's StrLen_or_IndPrt arguement?

$
0
0

I still can't figure out after reading SDK http://msdn.microsoft.com/en-us/library/windows/desktop/ms710963(v=vs.85).aspx

As far as i know ,when valuetype is SQL_C_CHAR, the StrLen_or_IndPtrargument point to SQL_NTS.

vauletype = SQL_C_FLOAT,SQL_C_ULONG.. the  StrLen_or_IndPtr argument point to SQL_NTS is 0.

how about TIME AND DATA, GUID type?

Is there a conclusion?

Your help will be  appreciated


how to track dependencies across linked servers

$
0
0

Is there a way to see dependencies across a linked server?  For example if someone removes columns from a table that is referenced in a view that is on a different server (using linked server) is there anyway to track that dependency? 

Thanks,


Laura

Visual Basic - Adding an item to a dropdownlist before/after data population

$
0
0

Hello there, I am a relatively new programmer who is currently using Visual Studio 2010 and coding Visual Basic.

I am attempting to add a starting index, a placeholder for a user to select one of the items below it, to my dropdownlist before or after it gets populated by a datatable via SQL, but no such luck.

Here is the code where I am pulling the data from the server and the following bit of code is where I am calling it when the object loads:

    ''' <summary>
    ''' Fill Plu and PluId info DDL
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ddlGetPluInfo()

        'Fetch Plu and PLU Id info from data access class
        ddlPluCode.DataSource = DataAccess.GetPluInformationDdl()
        ddlPluCode.DataBind()
    End Sub

Private Sub ddlPluCode_Load(sender As Object, e As System.EventArgs) Handles ddlPluCode.Load If IsPostBack = False Then 'Call procedure to get Plu and Commodity information ddlGetPluInfo() End If End Sub



JDBC Connection to SQLServer with windows Auth using user and password

$
0
0

Hi,

I am connecting from java app to sqlserver. I need to connect to with technical windows user/password with windows authentication. I am able to connect with logged on user but not with different windows user because it ignore my user name password if integrated security is true. I could connect using jtds driver but not with jdbc. It will be great help for me to know if its possible.

Thanks,CP

Viewing all 4164 articles
Browse latest View live


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