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

MySQL 5.1 SELECT WHERE Statment

$
0
0

Hi everybody;

I have built a SQL database and table and am trying to query records by user input (textbox.text).

I can query the entire database by the SELECT command as expected.  However, when I try to add in the WHERE clause to the SQL statement, it constantly says it can't find a record in the column specified that matches the user input.  To make sure I am processing the correct information, I have verified  the column name is typed correctly, I have tried querying by ID (auto number primary key field), I have tried querying by hard coded variable instead of user input into a control, I have copied and pasted all information including search variable into SQL SELECT syntax to ensure nothing had changed or was being change, I have tried using "" and '' and all kinds of variations, I have tried using @ to make the variable a parameter, I have tried + for the user input control.........I have tried EVERYTHING I can think of at this point........I'm at a loss at this point and have ZERO idea what else to try outside of the 246 GOOGLE searches I have done over the past 15 hours.  Here is 1 of the TONS of variations of the SQL SELECT WHERE statement I have tried....again, if I remove the WHERE clause the SELECT statement works great....so the issue seems to be from WHERE to the end of the statement:

 
Imports System.Windows.Forms
Imports MySql.Data.MySqlClient

Public Class OfficeAddressPreview

    Dim ServerString As String = "Server=localhost;User Id=root;Password=*******;Database=siteaddresses"
    Dim SQLConnection As MySqlConnection = New MySqlConnection
    Dim Command As New MySqlCommand
    Dim output As New DataTable

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub OfficeAddressPreview_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        SQLConnection.ConnectionString = ServerString
        OfficeSiteAddressDGV.DataSource = Nothing

        Try
            Dim user_content As String
            user_content = OfficeERFApplication.AttentionToTextBox.Text
            Command = New MySqlCommand("SELECT * FROM site_addresses WHERE Tech_Name =" & Chr(34) & OfficeERFApplication.AttentionToTextBox.Text & Chr(34))
            Dim MySqlA As New MySqlDataAdapter(Command)
            MySqlA.SelectCommand.Connection = SQLConnection
            MySqlA.Fill(output)

            If output.Rows.Count = 0 Then

                output = Nothing
                MsgBox("No data available for the listed tech, please verify the tech's name is spelled as it is in Coventry's Active Directory service.  If you have spelled the name correctly, you can add the tech and corresponding site by clicking the Add button on this page.", 0, "Error: No Record Found")

            Else

                OfficeSiteAddressDGV.DataSource = output

                MsgBox("Please select the appropriate location from the following list.  If the correct office is not listed, click the Add button to create a new shipping address for this tech.")

            End If

        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

    End Sub

End Class

One last time, There are 2 forms, Form1 (Parent (OfficeERFApplication)) and Form2 (Child Dialog Box(OfficeAddressPreview)).

On OfficeERFApplication, the user fills in AttentionToTextBox with a person's name then hits the enter key.  Enter key opens Form2 (OfficeAddressPreview) Dialog Box and starts the connection to SQL database.  At this point, if I remove from WHERE on in the SELECT statement, the entire table is shown properly in the DGV, but as soon as I add any form of the WHERE clause to the SELECT statement, it queries nothing as a result, it says in the column I am searching, the variable I supply  is not found.  Sorry for how all over the place I am on this post but I've been up over 48 hours programming and the past 15 hours has been spent on this 1 single issue.....this one single line of code (and yes this is my first time working with SQL in this complex of a manner).....yes I am a very persistent person LOL. 

And please, for all of you out there that quick scanned over this post and are now thinking "Well why don't you" or "that's stupid" or "why would you".....just please don't.......over 2 days up coding straight........not in the mood LOL.....I'm just simply looking for a working solution to what I have already....there's a reason I do everything I do the way I do it.....no offense.

Thank you for all of your help and training ladies and gentleman.


Connecting to a user created table

$
0
0

I have a SQL Server 2012 database where I create tables on the fly for reports.

These tables are created as Domain\UserName.TableName

I then try to run a Crystal Report and it reads from TableName not from Domain\UserName.TableName.

Needless to say, the reports are displaying the wrong data.

How do I connect to the Domain\UserName.TableName within my VB.NET code?

getting login failed for user 'nt authority\anonymous logon' after deploying asmx web service through IIS.

$
0
0

Hi,

I just deployed my asmx web service through IIS and got the url as http://localhost/ServiceLayer/service.asmx

it gives me this error login failed for user 'nt authority\anonymous logon'.

However, when running through VS 2010, it works just fine and connects to the database. Any help on this? I am using windows 7 with windows authentication and impersonation to true. 

ODBC Connection Error

$
0
0

hi,

anyone can help me. i have a issue to connection Apps to SQL 2012. using ODBC.

we already create the DNS user and DNS ODBC Data Source Administration, but always failed

Please advice

this is a message error :

2013.07.12 14:21:39 OCSQL: SQL code 0 : IM002 : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

2013.07.12 14:21:39 OCSQL: SQL code 0 : 01S00 : [Microsoft][ODBC Driver Manager] Invalid connection string attribute

2013.07.12 14:21:39 OCSQL: SQL code 0 : IM002 : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

2013.07.12 14:21:39 OCSQL: SQL code 0 : 01S00 : [Microsoft][ODBC Driver Manager] Invalid connection string attribute

2013.07.12 14:21:39 Failed to Connect to the Database

thanks for your support :)

Data is Null. This method or property cannot be called on null values

$
0
0

Hi,

I need some help with my program I am populating text boxes with data from a SQL Data BAse, but sometimes the values are "NULL" and so i get the following error : "Data is Null. This method or property cannot be called on null values"

How can i write it so the reader ignores the null value and continues or puts in a blank??

any help greatly appreciated.

Here is the code: 

written in Visual Studio 2010 - Windows Form Application (c++) 

private: System::Void listBoxCustomers_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {

			 String^ ListBoxVal=listBoxCustomers->Text;

			 String^ constring=L"datasource=127.0.0.1;port=3306;username=root;password=root";
				 MySqlConnection^ conDataBase=gcnew MySqlConnection(constring);
				 MySqlCommand^  cmdDataBase=gcnew MySqlCommand("select * from equipe.customers where name ='"+ListBoxVal+"';",conDataBase);
				 MySqlDataReader^ myReader;

				 try {
					conDataBase->Open();
					myReader=cmdDataBase->ExecuteReader();

					if(myReader->Read()){

							String ^ companyVal = myReader->GetString("company");
							txtCompany -> Text = companyVal;

							String ^ address1Val = myReader->GetString("address1");
							txtAddress1 -> Text = address1Val;
							String ^ address2Val = myReader->GetString("address2");
							txtAddress2 -> Text = address2Val;

							String ^ cityVal = myReader->GetString("city");
							txtCity -> Text = cityVal;

							String ^ stateVal = myReader->GetString("state");
							txtState -> Text = stateVal;

							String ^ zipVal = myReader->GetString("zip");
							txtZip -> Text = zipVal;

							String ^ nameVal = myReader->GetString("name");
							txtName -> Text = nameVal;
							String ^ idVal = myReader->GetString("id");
							txtId -> Text = idVal;
					}

				 }	catch(Exception^ex){
						MessageBox::Show(ex->Message);
					}

		 }

Thanks,

Ariel

passing column names and table name as parameters to function return value not working

$
0
0

ALTER FUNCTION [dbo].[UNIQUE_COLUMN_VALUE] (@var_pool_key INT,
   @var_in_table_name VARCHAR,
   @var_in_field_name VARCHAR)

   RETURNS  NVARCHAR(25)

AS

   BEGIN

    DECLARE @return_value_argument NVARCHAR(25)
    DECLARE @sql VARCHAR(250)


    SET @sql = 'SELECT ' + @return_value_argument + '= MAX(@var_in_field_name) + 1 FROM ' + @var_in_table_name + 'AS A WHERE A.POOL_KEY = ' + CONVERT(VARCHAR,@var_pool_key)  

    EXECUTE @SQL


    if (@return_value_argument = NULL)
    begin
        SET @return_value_argument = 1
    end

    RETURN @return_value_argument

   END

--------------------Execute function

SELECT [CCMS].[dbo].[UNIQUE_COLUMN_VALUE] (
  1625
  ,'INSTRUMENT_10001'
  ,'SESSION_ROW_KEY')
GO

Error

======

Msg 557, Level 16, State 2, Line 1
Only functions and some extended stored procedures can be executed from within a function.

Please help what to do?

                        

Highly Volatile Table. Lots of Inserts & Deletes, Hardly every Read and small amount of data.. Persistent Message Store basically.

$
0
0

I have a table that is used to persist messages/events which means data is inserted and deleted over and over and hardly ever read and usually there is limited amount of data in it... since a row is inserted... the event processed and then the row is deleted. The data in it only lives a short time.

I am getting deadlocks on that table trying to delete by the primary key. How can I reduce the locking on this table and prevent deadlocks? (delete from ops_event where "pkid" = ?)

Is there anything like the DB2 "Volatile" keyword for the table?

Thanks!




hibernate.cfg.xml and SQL-Server 2012

$
0
0

Hi!

I am trying to use the MS-SQL-Server 2012 with Hibernate and have some difficulties to create the hibernate.cfg.xml.

Has someone his Version to share, please?

Also I'd like to know if there might be a chance to find the JavaDoc for the SQL-Server-Driver?

Thank you!!


linked server to another linked server

$
0
0

I need to create a linked server (X) on 64 bit machine to another linked server (Y) which is on a 32 bit machine.

I need to do so because (Y) is used to read from another "database" (Z), and I could not find a way to query (Z) from a 64 bit machine because of drivers incompatibility with 64 bit, and this is why I'm using (Y) as an intermediate server. the problem is that when I create (X) i can see all the database on the 32 bit server but I can't see the linked servers there. is there a way to make (Y) appear as a normal database ? or is there a way to create (X) linked to (Y), when (Y) is another linked server? 

Cannot connect from windows 7 to a sql server 2008 R2 instances running in a windows 2008 r2 via Static IP

$
0
0

We have an SQL 2008 R2 running in a windows 2008 R2 Server with a static IP but we are unable to connect to this server from a particular windows 7 32 bit client machine.

But we can very well successfully connect to this server from other machines running win XPs and win7s

Is there any settings specifically in win7 that should be configured ?

or is there any modem settings ?

What all way should we attempt to get this right ?

Its very urgernt and hope someone will answer it soon

Thanks in advance


link server error

$
0
0

Hi,

 

I have one situation here, when ever this particular query is executed through linked server, the server hangs.The services get restarted.

 

In the error log, I got a stack dump error.

 

Query :

select*

--INTO #OMNIRELATIONSHIPS

fromopenquery(BRTOOMNI,'Select a.CUST_ID,c.LASTEXIT_DEDUPE,c.apprefno as APPREF, a.firstname AS FIRST_NAME,a.midname AS MIDDLE_NAME,a.lastname  as LAST_NAME,

--a.ShortName Short_Name,

 a.DATEOF_BIRTH Contact_DOB,

 -- '''' as Contact_Status,

 a.ENTITY_TYPE As Contact_Type,

a.SEX Gender, a.MARITAL Marital_Status, a.bank_name1 Bank_Account_1, a.bank_name2 Bank_Account_2,

a.PANno PAN,b.ADDR_MOBILENO MOBILE,b.ADDR_PH1_NO As Res_Phone,b.ADDR_PH2_NO As Off_Phone,b.addr_ph1_no As Phone_1,

b.addr_ph2_no As Phone_2,'''' As Phone_3,'''' As Phone_4, '''' As Phone_5,b.ADDR_EMAILID Email,

b.ADDR_FIRSTLINE Address_Line_1,b.ADDR_SECONDLINE Address_Line_2,

b.addr_thirdline As Locality,  b.ADDR_CITY CITY,'''' District,b.ADDR_STATE STATE,b.ADDR_ZIPCODE ZIP_CODE,

b.ADDR_COUNTRY_DESC Country,'''' As Alt_Address_Line_1, '''' As Alt_Address_Line_2,   

'''' as Alt_Mobile, '''' As Alt_Off_Phone, '''' as Alt_Res_Phone,'''' As Alt_Email, b.ADDR_LANDMARK LANDMARK,     

'''' As Contact_Owner

--'''' As ContactOwnerID,'''' As Status_Code,'''' As Layout

From hlbp_exttable c, SLBP_ENTITY a, (select * from slbp_addr@uat2rpt where addr_type = ''CURRENT RESIDENCE'') b --,punit_appref e        

Where c.customer = a.record_id and a.record_id = b.addr_parentid

AND trunc(c.LASTEXIT_DEDUPE)=trunc(sysdate-1)

--nd c.apprefno = e.appref

--and c.apprefno = ''13297840''

and a.CUST_ID is not null')

 

The 3 tables given in the query has data on around 22 lakhs to 1 crore.

 

Duda general C#

$
0
0

Buenas, estoy haciendo un programa simple en C# que utilizaría en la empresa para hacer consultas en SQL Server y al dar click en "consultar" muestre los resultados. La complicación es que el query depende de lo que quiere consultar el usuario, para ser más claro dejo el código:

#region CNX STRING
                    cnx.Open();
                    string query = "SELECT " + comboBoxDato.SelectedItem.ToString() +
                           " FROM " + comboBoxBase.SelectedItem.ToString() +
                           " WHERE letra='" + textBoxLetra.Text +
                           "' and " + comboBoxDatoDesc.SelectedItem.ToString() +
                           "='" + textBoxValDato.Text + "'";
                    SqlCommand cmd = new SqlCommand(query, cnx);
                    cmd.ExecuteNonQuery();
                    cnx.Close();
                    #endregion

Se me complica cuando tengo que mostrar el resultado en la DataGridView, probé de muchas maneras, ninguna dio resultados. Espero su pronta ayuda!

bcp: The DSN specified an unsupported driver.

$
0
0

I downloaded Microsoft® Command Line Utilities 11 for SQL Server® (MsSqlCmdLnUtils.msi).
I also have Microsoft® ODBC Driver 11 for SQL Server® - Windows (msodbcsql.msi) installed.

I created a DSN named SSRV_OUT, and chose driver "ODBC Driver 11 for SQL Server".

When I run
E:\>"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\bcp.exe" DB.sch.TABLENM out tablenm.dat -D -SSRV_OUT -T

I get this error:
The DSN specified an unsupported driver.
Why is that?

I tried to create another DSN using the "SQL Server Native
Client 11.0"
And the same command as above with the new DSN, results in an access violation.

I checked that when the -D option is not used, and -S refers to the server name, the execution uses"ODBC Driver 11 for SQL Server".  Does -D work on Windows?

Creating a Income & Expenditure Table.

$
0
0

I have to tables in my database- 1) Accounts_Table & 2) Ledger_Table(its the master table from where I will be picking up the Narration Column).

The Accounts_Table columns are- [ipkAcountId], [SNo], [dDate], [ifkCreditId], [ifkDebitId], [fAmount], [vBoardName], [vType], [ifkAcademicYearId], [vNarration]

The Ledger_Table columns are- ipkLedgerPartyCodeId(let say it as code), vLedgerPartyName, vLedgerPartyCode, vPartyType

Now I have to make a crystal report and show it via .net where the report will contain columns- Code, Description, Income, Expenditure.

I am writing down the sql query as:

Accounts_Table b

(select * from Ledger_Table where vPartyType='Income' or vPartyType='Expense') as "a" where b.ifkDebitId=a.code or b.ifkCreditId=a.code

(select a.code, a.vLedgerPartyName, sum(case b.ifkDebitId=a.code then 1 else -1)*fAmount) group by code, desc order by code

Nothing fruitful is coming. Please help any one so that I can show the desired four columns in the report. What query shall I use, please help.

Thanks in advance.


Pradeep(PKM)

Difference in initialilizing a class in difference ways

$
0
0

Suppose i have a class "TEST" What is the difference between

TEST obj = new TEST();

and

TEST obj = null;

Thanks


how to delete rows

$
0
0

hi

i have a  table below like :

table1 ->Name

             Age

             Date

             Tel

and mytable no have id columns

now i 'll find "Kia","20","2012","111111" and delete it

please help me

thanks

  

Does Select query Lock the table

$
0
0

Hi,

Does Select query Lock the table or only Insert,Update and Delete use to lock the table.

SQL Server 2005 Intermittent Error 18456 Severity 14 State 8

$
0
0

I have read through all the forum posts on this error.  I know that it is supposedly a "Password Mismatch".  HOwever - our applications use this login all the time with no issues.  The problem is intermittent and actually does not affect the users of the programs, that I know about.  however, I will occasionally get the error message showing up in both server logs, as well as emailed to me (due to email reporting I built into my .Net website).  The error is 18456 Severity 14 State 8.  The query triggering the errors varies.  In fact, I changed the login ID and password to a different one to see if that helps on some of the programs in question.  This did not help - now the errors thrown say the same thing, only with the new login ID as the culprit.

Any ideas?

Error: 18456, Severity: 14, State: 8.

Below is the error report I get from my website:

Connection String: server=xxx.xx.xx.x;database=xxxx;uid=xxxxxxx;pwd=xxxxxxxxx;
Command Text: SELECT * FROM kpmOrderHistoryHeader WHERE OrderNumber = @OrderNumber ORDER BY SubmitDate DESC
Command Timeout: 60
Connection Timeout: 45
Database Name: System.String[]
Page Name: OrderSuccess.aspx
Error Message: Login failed for user 'KPMSQLUser81'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at Kpmedi2Lib.Dal.ExecuteReader(SqlCommand Cmd) in C:\VS2006 Web Projects\KPMEDI.com\Kpmedi2Lib\Dal.cs:line 88


Jesse

Ms-Access Oledb Providers

$
0
0

I need the Oledb Porvider so I can connect to Ms-Access.

I opened up Data Link Properties a And the Providers is not there.


shawnrye

Transação distribuida no SQL Server

$
0
0

Boas!!

Sou iniciante em banco de dados e estou com uma duvida. Tenho uma integração para fazer com outra base de dados (pra ser específico é o OpenEdge Progress), e para fazer a integração entre SQL Server x Progress estou usando LInkedServer.

Para fazer um select ou insert, faço a seguinte instrução:

INSERT OPENQUERY("linked-banco", 'SELECT id FROM PUB."tabela" ') VALUES (4)

Fazendo via comando eu consigo normalmente. Só que eu necessito fazer isso via TRIGGER. Se eu montar uma trigger com essa instrução ele retorna um erro dizendo:

"The operation could not be performed because OLE DB provider "MSDASQL" for linked server "linked-banco" was unable to begin a distributed transaction."

Alguem pode me ajudar se há alguma forma de eu "desativar" essa transação distribuida, ou conseguir passar isso?

att

Rafael

Viewing all 4164 articles
Browse latest View live


Latest Images

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