Need Help With ExecuteReader() Command

Jan 18, 2008

HI
 I am having problem with my Execute Reader. I am trying to insert values from 2 different tables into another table.
 
   SqlCommand comm2;
SqlDataReader reader2;
/* Grabs the stuff out of the database */
comm2 = new SqlCommand("SELECT HiraganaCharacter,HiraganaImage FROM Hiragana", getConnection());
/* opens the database */
comm2.Connection.Open();
/* starts the reader */
reader2 = comm2.ExecuteReader();
/* goes through the first array list */
for (int i = 0; i < checkedLetters.Count; i++)
{ /* find the data by using the array list value as a where clause */
comm2.CommandText = "SELECT HiraganaCharacter,HiraganaImage FROM Hiragana WHERE HiraganaCharacter ='"
+ checkedLetters[i] + "'";
/* reads through the data */
reader2.Read(); /* puts the ID- this id was set somewhere else */
CommQuickLinksItems.Parameters["@QuickLinkID"].Value = QuickLinkId;
CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["HiraganaCharacter"].ToString();
CommQuickLinksItems.Parameters["@CharacterImagePath"].Value = reader2["HiraganaImage"].ToString();

CommQuickLinksItems.ExecuteNonQuery();
}

for (int j = 0; j < checkedLettersKata.Count; j++)
{
comm2.CommandText = "SELECT KatakanaCharacter,KatakanaImage FROM Katakana WHERE KatakanaCharacter ='"
+ checkedLettersKata[j] + "'";
reader2.Read();
CommQuickLinksItems.Parameters["@QuickLinkID"].Value = QuickLinkId; /* line it dies on */
CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["KatakanaCharacter"].ToString();
CommQuickLinksItems.Parameters["@CharacterImagePath"].Value = reader2["KatakanaImage"].ToString();

CommQuickLinksItems.ExecuteNonQuery();

}

CommQuickLinksItems.Connection.Dispose();
CommQuickLinksItems.Dispose();
comm2.Connection.Dispose();
comm2.Dispose(); My first question is there a better way to setup a SqlCommand to just get the connection and wait on the Command object text? Right now I am doing comm2 = new SqlCommand("SELECT HiraganaCharacter,HiraganaImage FROM Hiragana", getConnection());Which is kinda pointless since in the for loop I change the command to something different right away. At the same time though I don't really want to make a new SqlCommand object in the for loop since then everytime it goes through the loop it would then re grab the connection what I find pointless tooNow the problem How I have it right now it does not grab the right stuff. The first for loop works great and everything gets inserted. The next loop does not work It seems like it it trying to take the data from the first for loop and insert that stuff again since I get this error System.IndexOutOfRangeException was unhandled by user code
Message="KatakanaCharacter"
Source="System.Data"
StackTrace:
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.SqlClient.SqlDataReader.get_Item(String name)
at Practice.QuickLinks() in g:WebsiteJapanesePractice.aspx.cs:line 385
at Practice.btnQuickLink_Click(Object sender, EventArgs e) in g:WebsiteJapanesePractice.aspx.cs:line 411
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
Basically what I did was for the first loop I chose 2 items and for the 2nd loop I chose 3 items. When it died on this line  CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["KatakanaCharacter"].ToString();The value was "i" but that was one of the values I choose for the first for loop. It should have been either u,e,o. So I am not sure what I am doing wrong. I thought as long as I change the Command text I would not need to do anything else but it seems like I am missing something.  

View 5 Replies


ADVERTISEMENT

Problems With : SqlDataReader = Command.ExecuteReader()

Apr 11, 2007

I am currently tryinh to have this variable declared :   Dim SQLLecteur As SqlDataReader = Command.ExecuteReader()And receiving the following error : 'ExecuteReader' is not member of 'String'.1. The ExecuteReader was not present in the list following the Command.2. The variable is declared from a : Public Shared Sub3. This sub is located in a code library referenced in the web.config as a namespace : <add namespace="PAX20070409" />4. If used directly in the .vb file within this sub : Protected Sub btnConnection_Click, I am not receiving any errors about the Dim.It is pretty clear why the code is not working, but I have not been able to find a way to fix the problem. I am currently trying to find a way to make the Dim work from within my code library. If you have any idea on how this could be achieve, it would be greatly apreciated.Thank you :)RV3 

View 4 Replies View Related

Command Doesnt Support Executereader

Nov 26, 2006

Code:

connstr = "my connction info"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open connstr

Set objCmd=Server.CreateObject("ADODB.Command")
set objCmd.ActiveConnection = objconn

objCmd.CommandText = "my stored procedure"
objCmd.CommandType = 4

objcmd.parameters.append objcmd.createparameter("@itemcheckduplicate", 200, 1, 30, itemadd)
SqlDataReader forduplicate = objcmd.ExecuteReader()

my procedure :

@itemcheckduplicate varchar(30)

as
select sw_item_itemid
from sw_item
where sw_item_item like @itemcheckduplicate



why my command doesnt support ExecuteReader ?

Microsoft VBScript runtime error '800a01b6'

Object doesn't support this property or method: 'ExecuteReader'

View 2 Replies View Related

Using ExecuteReader() And GetString()

Mar 3, 2008

Hi.
I'm trying to read data from a database. This is my code:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
connection.Open();SqlCommand cmd = new SqlCommand(sql, connection);
myReader = cmd.ExecuteReader();if (myReader.Read())
{
name1TextBox.Text = myReader.GetString(1);
addr1TextBox.Text = myReader.GetString(2);
code1TextBox.Text = myReader.GetString(5);
tel1TextBox.Text = myReader.GetString(6);
fax1TextBox.Text = myReader.GetString(7);
:
:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The above code works fine until one of the GetString calls trys to return NULL (in this case myReader.GetString(5)).
In other words, this code will run through about 30 rows of data until it runs in to a NULL entry for one of the columns.
At that stage it's too late. I'm not allowed call GetString( ) on a NULL value.
Is there anyway I can test the column entry before calling GetString( ).
Regards (& thanks in advance)
Garrett

View 4 Replies View Related

Number Of Row Returned By ExecuteReader

Nov 14, 2007

when I execute the line:
reader = comm.ExecuteReader();
Is there a way to get a count of the number of records returned (the query is a SELECT with no count in it)? I want to vary the display of the results set based on the number of records returned.
For example if no records are returned I want it to display nothing, if one, I want the header to be in the singular, but if more than one record is returned, I want it to display the header in plural form.
Here is my code snippet with further explanation of what I am trying to do:int Inumber = 0;foreach (string item in menuHeaders)
{string title = menuHeaders[Inumber];
sp.Value = menuHeaders[Inumber];
Inumber++;
conn.Open();reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
//Get the culture property of the thread.CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
//Create TextInfo object.TextInfo textInfo = cultureInfo.TextInfo;
// WHAT I AM TRYING TO DO....... Here I would like to wrap this with an if statement, if  Records returned by the reader are 0, skip while loop and header display
// If one, then display in singular and if 2 add an s to the title. Convert to title case and display.content.Text += "<H3>" + textInfo.ToTitleCase(title) + "</H3>";while (reader.Read())
{
content.Text += "<a href='" + reader["website"] + "'>" + reader["f_name"] + reader["l_name"] + "</a>"+ ", " +reader["organization"]+"<br />";
}
//Close the connection.
reader.Close();
conn.Close();
}

View 1 Replies View Related

Getting Data From An ExecuteReader Variable

Jan 28, 2008

Hi all,I have a script which I am running to get the minimum date from a database table.I've connected to the database and run the sql but when I try to get the result i get an error saying "No data exists for the row/column."This is the code I have for it at the moment.1 Dim mySql As String = "SELECT MIN(LOSS_DATE) AS minDate FROM dbo_CLAIMS"
2 Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|NexusHolding.mdb;Persist Security Info=True"
3 Dim dbCon As New OleDbConnection(connectionString)4
5 dbCon.Open()6
7 Dim dbComm As New OleDbCommand(mySql, dbCon)8 Dim dbRead = dbComm.ExecuteReader()9 Dim minDate As String = dbRead.GetValue(0)10
11 Response.Write(minDate)Thanks in advance for any help. 

View 3 Replies View Related

Catch Raiserror From ExecuteReader

Feb 27, 2004

Hi. I am executing a stored procedure. The stored procedure raises an error and all I need is to catch this error. Pretty simple, but it only works with an ExecuteNonQuery and not with an Executereader statement. Can anybody explain to me why this happens?

Here's the sp:

CREATE PROCEDURE dbo.rel_test
AS
select 1
raiserror ('My error.', 11, 2)
return
GO

Here's the ASP.Net page:

<% @Page Language="VB" debug="True" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Public Function RunSP(ByVal strSP As String) As SqlDataReader
Dim o_conn as SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
AddHandler o_conn.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)

o_conn.Open

Dim cmd As New SqlCommand(strSP, o_conn)
cmd.CommandType = System.Data.CommandType.StoredProcedure
Dim rdr as SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
rdr.Close()
cmd.Dispose()

Response.Write(o_conn.State)


End Function

Private Sub OnInfoMessage(sender as Object, args as SqlInfoMessageEventArgs)
Dim err As SqlError
For Each err In args.Errors
Response.Write(String.Format("The {0} has received a severity {1}, state {2} error number {3}" & _
"on line {4} of procedure {5} on server {6}:{7}", _
err.Source, err.Class, err.State, err.Number, err.LineNumber, _
err.Procedure, err.Server, err.Message))
Next
End Sub

Sub Page_Load(sender as Object, e as EventArgs)
RunSP("rel_test")
End Sub
</script>

View 2 Replies View Related

Stored Procedure And ExecuteReader

Jul 5, 2005

I am not seeing why this is not executing the reader, it just goes right by it when stepping through the code...
command.CommandType = CommandType.StoredProcedure;
// course
command.Parameters.Add( "@courseId", courseId );
// Parameter: LessonName
SqlParameter sLessonName = command.Parameters.Add( "@lessonName", SqlDbType.VarChar );
sLessonName.Size = 256;
sLessonName.Direction = ParameterDirection.Output;
// error code
SqlParameter pErrCode = command.Parameters.Add( "@errCode", SqlDbType.Int );
pErrCode.Direction = ParameterDirection.Output;
// execute the stored procedure
SqlDataReader spResults;
conn.Open();
spResults = command.ExecuteReader();
while( spResults.Read() ) // It never steps into the while statement like the reader is completed
{
RetrieveObjId objNames = new RetrieveObjId( spResults.GetString( 0 ));
searchResults.Add( objNames );
}
spResults.Close();And the stored procedure is.....CREATE  PROCEDURE dbo.retrieveLessonNames @courseId  VARCHAR(20), @lessonName  VARCHAR(256) OUTPUT, @errCode         INT               OUTPUT  ASBEGIN
 SELECT @lessonName = objName       FROM   objStructure WHERE  courseId = @courseId
 SET @errCode = 0  RETURN @errCode HANDLE_APPERR: SET @errCode = 1  RETURNHANDLE_DBERR: SET @errCode = -1  RETURNENDGOSuggestions?Thanks all,Zath

View 3 Replies View Related

Intermittent ExecuteReader Problems

Oct 26, 2006

I have VS 2005 and SQL CE 3.0. I sometimes get the a FileNotFoundException when I first use ExecuteReader. I believe this is because a dll has not been copied across because if I restart the emulator I can get it to work again.

Do I need to add a cab file/dll to my project to stop this happening?

Thanks

Emmet

View 1 Replies View Related

ExecuteReader: Connection Property Has Not Been Initialized.

Apr 23, 2008

I'm writing my first vb.net app.  Have a default page that uses a persons network login to query a database to get all their  timekeeper id, firstname, last name, etc.  But I keep getting this error.  (My code is below)  What am I missing??? 
ExecuteReader: Connection property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: ExecuteReader: Connection property has not been initialized.Source Error:



Line 21: conn.Open()
Line 22:
Line 23: reader = comm.ExecuteReader()
Line 24: If reader.Read() Then
Line 25: EmployeesLabel.Text = reader.Item("tkinit") 
<script runat="server">Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)Dim conn As SqlConnectionDim comm As SqlCommandDim reader As SqlDataReaderDim connectionString As String = ConfigurationManager.ConnectionStrings("xxxConnectionString").ConnectionStringcomm = New SqlCommand("Select top 1 tkinit, tklast, tkfirst +' '+ tklast as fullname from txxx WHERE login = @login)", conn)comm.Parameters.Add("@Login", Data.SqlDbType.VarChar)comm.Parameters("@Login").Value = Me.User.Identity.Name.Substring(User.Identity.Name.IndexOf("") + 1)conn = New SqlConnection(connectionString)conn.Open()reader = comm.ExecuteReader()If reader.Read() ThenEmployeesLabel.Text = reader.Item("tkinit")FirstLastName.Text = reader.Item("fullname")End Ifreader.Close()conn.Close()End Sub</script>

View 1 Replies View Related

ExecuteReader: Connection Property Has Not Been Initialized.

Mar 11, 2005

I have a web form that is generating an error and I can't seem to figure out why for the life of me. Below is the code:


Private Sub VerifyNoDuplicateEmail()
Dim conn As SqlConnection
Dim sql As String
Dim cmd As SqlCommand
Dim id As Guid
sql = "Select UserID from SDCUsers where email='{0}'"
sql = String.Format(sql, txtEmail.Text)
cmd = New SqlCommand(sql, conn)
conn = New SqlConnection(ConfigurationSettings.AppSettings("cnSDCADC.ConnectionString"))
conn.Open()
Try
'The first this we need to do here is query the database and verify
'that no one has registed with this particular e-mail address
id = cmd.ExecuteScalar()
Response.Write(id.ToString & "<BR>")
Catch
Response.Write(sql & "<BR>")
Response.Write("An error has occurred: " & Err.Description)
Finally
If Not id.ToString Is Nothing Then
'The e-mail address is already registered.
Response.Write("Your e-mail address has already been registered with this site.<BR>")
conn.Close()
_NoDuplicates = False
Else
'It's safe to add the user to the database
conn.Close()
_NoDuplicates = True
End If
End Try
End Sub

Web.Config
<appSettings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add key="cnSDCADC.ConnectionString" value="workstation id=STEPHEN;packet size=4096;integrated security=SSPI;data source=SDCADC;persist security info=False;initial catalog=sdc" />
</appSettings>


Can anyone show me the error of my ways?

Thanks,
Stephen

View 4 Replies View Related

ExecuteReader: CommandText Propert Has Not Been Initialized

Oct 2, 2007



Hello All,

I receive the following error when attempting to preview or run a simple report:

ExecuteReader: CommandText propert has not been initialized


I have searched the help website and other forums, but I have had no success.

I am new to Reporting Services and this is one of the first reports I have created. All of my reports have this error.

Any ideas?

Thanks in advance.

View 1 Replies View Related

ExecuteReader Error A Parameter Is Missing [Paremeter Ordinal = 1]

Sep 24, 2007

Hello and thanks in advance.

This error was received executing a SqlCeCommand method of ExecuteReader();

I have only found 3 hits in Google about this error and the time it was asked in a MS forum it was not answered. I need an answer, please.

bombar...see code below


SqlCeDataAdapter adp = null;

adp = new SqlCeDataAdapter();

SqlCeCommand cmd;

cmd = _Con.CreateCommand();

cmd.CommandType = CommandType.Text;

cmd.CommandText = "insert into InventoryCounts(DateTime,WarehouseID,PartID,LotID,UserName,Count) VALUES(?,?,?,?,?,?)";

adp.InsertCommand = cmd;

cmd = _Con.CreateCommand();

cmd.Parameters.Clear();

SqlCeParameter p1 = cmd.Parameters.Add("DateTime",SqlDbType.DateTime);

SqlCeParameter p2 = cmd.Parameters.Add("WarehouseID",SqlDbType.NChar,20);

SqlCeParameter p3 = cmd.Parameters.Add("PartID", SqlDbType.NChar,20);

SqlCeParameter p4 = cmd.Parameters.Add("LotID", SqlDbType.NChar,20);

SqlCeParameter p5 = cmd.Parameters.Add("UserName", SqlDbType.NChar,20);

SqlCeParameter p6 = cmd.Parameters.Add("Count", SqlDbType.Int);

p1.Value = Convert.ToString(DateTime.Now);

p2.Value = "Warehouse1";

p3.Value = txtBPartIDShow.Text;

p4.Value = txtBLotIDEntry.Text;

p5.Value = "JHB";

p6.Value = Convert.ToInt32(txtBCountEntry.Text);



cmd = _Con.CreateCommand();

cmd.CommandType = CommandType.Text;

cmd.CommandText = "insert into InventoryCounts(DateTime,WarehouseID,PartID,LotID,UserName,Count) VALUES(?,?,?,?,?,?)";

cmd.Prepare();

cmd.ExecuteReader();

View 4 Replies View Related

System.InvalidOperationException: ExecuteReader: Connection Property Has Not Been Initialized.

Jan 29, 2008

Hi,

I have written a CLR Function in C#. The function works as expected except that I am trying to read data some data during the function call and get the following error:


Msg 6522, Level 16, State 1, Line 1

A .NET Framework error occurred during execution of user-defined routine or aggregate "fn_SLARemaining":

System.InvalidOperationException: ExecuteReader: Connection property has not been initialized.

System.InvalidOperationException:

at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)

at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)

at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)

at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)

at System.Data.SqlClient.SqlCommand.ExecuteReader()

at SLARemaining.SupportTimes.addSupportHours()

at SLARemaining.CalculateTimeRemaining.GetTimeRemaining(String openDate, Decimal SLADuration)

at UserDefinedFunctions.fn_SLARemaining(SqlDateTime DateFrom, SqlDateTime DateTo, SqlInt32 PriorityTime, SqlDecimal AdjustmentTime, SqlDecimal Status)

.


The main code for the function is this:


using System;

using System.Data;

using System.Data.SqlTypes;

using System.Data.SqlClient;

using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions

{

[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]

public static SqlString fn_SLARemaining(SqlDateTime @DateFrom, SqlDateTime @DateTo, SqlInt32 @PriorityTime, SqlDecimal @AdjustmentTime, SqlDecimal @Status)

{

SLARemaining.CalculateTimeRemaining remaining;

remaining = new SLARemaining.CalculateTimeRemaining();

int duration = Convert.ToInt32(PriorityTime.ToString());

if (!DateFrom.IsNull)

{

string date = DateFrom.Value.ToShortDateString() + " " + DateFrom.Value.ToShortTimeString();

SqlString result = remaining.GetTimeRemaining(date, duration);

return result;

}

else

{

return null;

}

}

};


The function calls the following method from another class:


public string[] addSupportHours()

{

string[] supportedHours = new string[28];

SqlDataReader dr;



SqlCommand cmd = new SqlCommand();

cmd.CommandText = "xxxxxxx"; //<-- commented out for this post

using (SqlConnection cn = new SqlConnection("context connection=true;"))

{

cn.Open();


dr = cmd.ExecuteReader();



while (dr.Read())

{
//do some stuff
}

cn.Close();

cn.Dispose();
}

The error message claims that the connection has not been initialized - can't work out why? Any help will be appreciated!

View 3 Replies View Related

ExecuteReader Requires An Open And Available Connection. The Connection's Current State Is Closed.

Apr 26, 2007

I am accessing SQL2005 with C# code using OleDbConnection.



A try and catch block catches the following error once a while between the Open() and Close() of the connection:

ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.



I do not even have any idea where to start to debug this. The ExecuteNonQuery() runs a delete SQL query. It works 99.9% of the time. I do not see anything wrong when this error happens.



Any hint would be greatly appreciated.



View 9 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

Feb 23, 2007

i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()        test.InsertCommandType = SqlDataSourceCommandType.Text        test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "                  test.InsertParameters.Add("roll", TextBox1.Text)        test.InsertParameters.Add("name", TextBox2.Text)        test.InsertParameters.Add("age", TextBox3.Text)        test.InsertParameters.Add("email", TextBox4.Text)        test.Insert() i am using UPDATE command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        test.UpdateCommandType = SqlDataSourceCommandType.Text        test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll                                                         123 "        test.Update()but i have to use the SELECT command like this which is completely different from INSERT and  UPDATE commands   Dim tblData As New Data.DataTable()         Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated                                                                                Security=True;User Instance=True")   Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)   Dim da As New Data.SqlClient.SqlDataAdapter(Command)   da.Fill(tblData)   conn.Close()                   TextBox4.Text = tblData.Rows(1).Item("name").ToString()        TextBox5.Text = tblData.Rows(1).Item("age").ToString()        TextBox6.Text = tblData.Rows(1).Item("email").ToString()       for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me

View 2 Replies View Related

Using A Variable In SSIS - Error - Command Text Was Not Set For The Command Object..

Nov 4, 2006

Hi All,

i am using a OLE DB Source in my dataflow component and want to select rows from the source based on the Name I enter during execution time. I have created two variables,

enterName - String packageLevel (will store the name I enter)

myVar - String packageLevel. (to store the query)

I am assigning this query to the myVar variable, "Select * from db.Users where (UsrName = " + @[User::enterName] + " )"

Now in the OLE Db source, I have selected as Sql Command from Variable, and I am getting the variable, enterName,. I select that and when I click on OK am getting this error.

Error at Data Flow Task [OLE DB Source [1]]: An OLE DB error has occurred. Error code: 0x80040E0C.
An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object.".

Can Someone guide me whr am going wrong?

myVar variable, i have set the ExecuteAsExpression Property to true too.

Please let me know where am going wrong?

Thanks in advance.








View 12 Replies View Related

Do Somebody Know How Long (in Chars) Script(command) Can Be Solved By SQL Command?

Aug 30, 2004

Do somebody know how long (in chars) script(command) can be solved by SQL Command?
Thanks

View 1 Replies View Related

What Command Is Used To Get Back The Privileges Offered By The GRANT Command?

Mar 10, 2007

reply.

View 1 Replies View Related

Command Text Was Not Set For The Command Object Error

Sep 19, 2006

Hi. I am writing a program in C# to migrate data from a Foxpro database to an SQL Server 2005 Express database. The package is being created programmatically. I am creating a separate data flow for each Foxpro table. It seems to be doing it ok but I am getting the following error message at the package validation stage:

Description: An OLE DB Error has occured. Error code: 0x80040E0C.

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object".

.........

Description: "component "OLE DB Destination" (22)" failed validation and returned validation status "VS_ISBROKEN".

This is the first time I am writing such code and I there must be something I am not doing correct but can't seem to figure it out. Any help will be highly appreciated. My code is as below:

private bool BuildPackage()

{




// Create the package object

oPackage = new Package();

// Create connections for the Foxpro and SQL Server data

Connections oPkgConns = oPackage.Connections;

// Foxpro Connection

ConnectionManager oFoxConn = oPkgConns.Add("OLEDB");

oFoxConn.ConnectionString = sSourceConnString; // Created elsewhere

oFoxConn.Name = "SourceConnectionOLEDB";

oFoxConn.Description = "OLEDB Connection For Foxpro Database";

// SQL Server Connection

ConnectionManager oSQLConn = oPkgConns.Add("OLEDB");

oSQLConn.ConnectionString = sTargetConnString; // Created elsewhere

oSQLConn.Name = "DestinationConnectionOLEDB";

oSQLConn.Description = "OLEDB Connection For SQL Server Database";

// Add Prepare SQL Task

Executable exSQLTask = oPackage.Executables.Add("STOCK:SQLTask");

TaskHost thSQLTask = exSQLTask as TaskHost;

thSQLTask.Properties["Connection"].SetValue(thSQLTask, "oSQLConn");

thSQLTask.Properties["DelayValidation"].SetValue(thSQLTask, true);

thSQLTask.Properties["ResultSetType"].SetValue(thSQLTask, ResultSetType.ResultSetType_None);

thSQLTask.Properties["SqlStatementSource"].SetValue(thSQLTask, @"C:LPFMigrateLPF_Script.sql");

thSQLTask.Properties["SqlStatementSourceType"].SetValue(thSQLTask, SqlStatementSourceType.FileConnection);

thSQLTask.FailPackageOnFailure = true;



// Add Data Flow Tasks. Create a separate task for each table.

// Get a list of tables from the source folder

arFiles = Directory.GetFileSystemEntries(sLPFDataFolder, "*.DBF");

for (iCount = 0; iCount <= arFiles.GetUpperBound(0); iCount++)

{


// Get the name of the file from the array

sDataFile = Path.GetFileName(arFiles[iCount].ToString());

sDataFile = sDataFile.Substring(0, sDataFile.Length - 4);

oDataFlow = ((TaskHost)oPackage.Executables.Add("DTS.Pipeline.1")).InnerObject as MainPipe;

oDataFlow.AutoGenerateIDForNewObjects = true;



// Create the source component

IDTSComponentMetaData90 oSource = oDataFlow.ComponentMetaDataCollection.New();

oSource.Name = (sDataFile + "Src");

oSource.ComponentClassID = "DTSAdapter.OLEDBSource.1";

// Get the design time instance of the component and initialize the component

CManagedComponentWrapper srcDesignTime = oSource.Instantiate();

srcDesignTime.ProvideComponentProperties();

// Add the connection manager

if (oSource.RuntimeConnectionCollection.Count > 0)

{


oSource.RuntimeConnectionCollection[0].ConnectionManagerID = oFoxConn.ID;

oSource.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(oFoxConn);

}

// Set Custom Properties

srcDesignTime.SetComponentProperty("AccessMode", 0);

srcDesignTime.SetComponentProperty("AlwaysUseDefaultCodePage", true);

srcDesignTime.SetComponentProperty("OpenRowset", sDataFile);

// Re-initialize metadata

srcDesignTime.AcquireConnections(null);

srcDesignTime.ReinitializeMetaData();

srcDesignTime.ReleaseConnections();

// Create Destination component

IDTSComponentMetaData90 oDestination = oDataFlow.ComponentMetaDataCollection.New();

oDestination.Name = (sDataFile + "Dest");

oDestination.ComponentClassID = "DTSAdapter.OLEDBDestination.1";

// Get the design time instance of the component and initialize the component

CManagedComponentWrapper destDesignTime = oDestination.Instantiate();

destDesignTime.ProvideComponentProperties();

// Add the connection manager

if (oDestination.RuntimeConnectionCollection.Count > 0)

{


oDestination.RuntimeConnectionCollection[0].ConnectionManagerID = oSQLConn.ID;

oDestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(oSQLConn);

}

// Set custom properties

destDesignTime.SetComponentProperty("AccessMode", 2);

destDesignTime.SetComponentProperty("AlwaysUseDefaultCodePage", false);

destDesignTime.SetComponentProperty("OpenRowset", "[dbo].[" + sDataFile + "]");



// Create the path to link the source and destination components of the dataflow

IDTSPath90 dfPath = oDataFlow.PathCollection.New();

dfPath.AttachPathAndPropagateNotifications(oSource.OutputCollection[0], oDestination.InputCollection[0]);

// Iterate through the inputs of the component.

foreach (IDTSInput90 input in oDestination.InputCollection)

{


// Get the virtual input column collection

IDTSVirtualInput90 vInput = input.GetVirtualInput();

// Iterate through the column collection

foreach (IDTSVirtualInputColumn90 vColumn in vInput.VirtualInputColumnCollection)

{


// Call the SetUsageType method of the design time instance of the component.

destDesignTime.SetUsageType(input.ID, vInput, vColumn.LineageID, DTSUsageType.UT_READWRITE);

}

//Map external metadata to the inputcolumn

foreach (IDTSInputColumn90 inputColumn in input.InputColumnCollection)

{


IDTSExternalMetadataColumn90 externalColumn = input.ExternalMetadataColumnCollection.New();

externalColumn.Name = inputColumn.Name;

externalColumn.Precision = inputColumn.Precision;

externalColumn.Length = inputColumn.Length;

externalColumn.DataType = inputColumn.DataType;

externalColumn.Scale = inputColumn.Scale;

// Map the external column to the input column.

inputColumn.ExternalMetadataColumnID = externalColumn.ID;

}

}

}

// Add precedence constraints to the package executables

PrecedenceConstraint pcTasks = oPackage.PrecedenceConstraints.Add((Executable)thSQLTask, oPackage.Executables[0]);

pcTasks.Value = DTSExecResult.Success;

for (iCount = 1; iCount <= (oPackage.Executables.Count - 1); iCount++)

{


pcTasks = oPackage.PrecedenceConstraints.Add(oPackage.Executables[iCount - 1], oPackage.Executables[iCount]);

pcTasks.Value = DTSExecResult.Success;

}

// Validate the package

DTSExecResult eResult = oPackage.Validate(oPkgConns, null, null, null);

// Check if the package was successfully executed

if (eResult.Equals(DTSExecResult.Canceled) || eResult.Equals(DTSExecResult.Failure))

{


string sErrorMessage = "";

foreach (DtsError pkgError in oPackage.Errors)

{


sErrorMessage = sErrorMessage + "Description: " + pkgError.Description + "";

sErrorMessage = sErrorMessage + "HelpContext: " + pkgError.HelpContext + "";

sErrorMessage = sErrorMessage + "HelpFile: " + pkgError.HelpFile + "";

sErrorMessage = sErrorMessage + "IDOfInterfaceWithError: " + pkgError.IDOfInterfaceWithError + "";

sErrorMessage = sErrorMessage + "Source: " + pkgError.Source + "";

sErrorMessage = sErrorMessage + "Subcomponent: " + pkgError.SubComponent + "";

sErrorMessage = sErrorMessage + "Timestamp: " + pkgError.TimeStamp + "";

sErrorMessage = sErrorMessage + "ErrorCode: " + pkgError.ErrorCode;

}

MessageBox.Show("The DTS package was not built successfully because of the following error(s):" + sErrorMessage, "Package Builder", MessageBoxButtons.OK, MessageBoxIcon.Information);

return false;

}

// return a successful result

return true;
}

View 2 Replies View Related

Sql TOP Command

May 19, 2007

Hi,I'm using the sql TOP command to retrieve the top N number of results where N is a value passed into the stored proc...eg: select TOP(@N) table.*from table...etc..if @N is not passed into the stored proc then by default i want it to select every row from the table. e.g to achieve something similar to...select table.*from table...how can i do this with with as few lines of code possible? thanks!      

View 4 Replies View Related

Need Help With Sql Command

Aug 26, 2007

Hello, i have this sql command:
sqlcommand2.CommandText = "Select Count(UserIP) From InboundTraffic Where InboundURL Contains('" & SiteDomain(i).ToString & "') and DateTimeReceived > #" & Last30Days & "#"
My problem is that it is counting every field in the coulmn UserIp even though every field under Inboundurl currently contains 'a' and SiteDomain has a value of something like google.com.  Should it not be returning nothing?  Thanks!

View 1 Replies View Related

Is There An SQL Command For This?

May 6, 2004

Okay I have a column

Red
Red
Blue
Yellow
Blue
Blue
Blue
Blue

I want to return the value that appears most i.e. in this case Blue.

Thanks

Ben

View 1 Replies View Related

The SQL Command For...

Sep 6, 2004

Hi!
Suppose a company has ten branches and a total employees of 10,000 ones. At the employees' table, how may I calculate the difference between every employee's salary to the average salary of own branch and write to the other field of table, just with a SQL Command?

Employee:
ID | Branch | Salary | DifferenceToAverage

Regards,
M.Sadegh Samiei

View 5 Replies View Related

SQL Command Help

Oct 21, 2004

There are 2 relevant fields in the table: SystemID & Description
For anything w/a SystemID of 1001, I want to add "ABC-" in FRONT of the description.

For example: If The description was XYZ and the systemID 1001, i want it to change to: ABC-XYZ

Thank you

View 1 Replies View Related

Bcp Command

Sep 29, 2005

I am using the bcp command to export  a bulk text file into the database,
bcp elearning.dbo.BulkData in mobile.txt -c -t,  -SZOHL-02 -Usa -P1234567890  -E
I have 6 fields in the table to which i am exporting data.One field is numeric and i have to set the identity to yes,It gives me an error string data trucncated. When i remove the identity field, i am able to export data.So, how do i tackle this prob?I used the -E attribute to keep the identity .But still i get the error. The text file has comma seperated fields.I am using sql server 2000
 

View 1 Replies View Related

BCP Command

Nov 2, 2000

Hello, i'm a junior progammer,
I must use the BCP command for create a file that is needed to be used by another program.I have my template to use EX.:

ASKOFE00001ASQSQOPSAZ000123324AAJISQ
ASDAJDIOW78708AMXOPSAJSMA565876979AA

I've tried but my result was 1 line whith ascii character.
Please help me.

Massimo Nardi

View 2 Replies View Related

Sql-command

Aug 24, 1999

Hi !

Does anyone know the sql-statement to check the actual length in a varchar2 columns.

For example in Oralce you can do this

select length(column_name) from table;

I want to check that a program hasn't been wriiten the whole column with spaces.

View 1 Replies View Related

Sql Command Again

Aug 26, 1999

Does anyone know if there is any possibility to create a copy of a table in the database something like:

create table table_copy as select * from table;

I have found the backup table tool kind of unreliable !

View 2 Replies View Related

Bcp Command

Dec 21, 2004

Hi all,

I am trying to run a .bat file with this bcp command.

BCP "database.dbo.state" OUT "C:TEMPstate.dat" -SServerName -U"userid" -P"password" -m1 -n -a65536 -E -q

However, it is not producing me a file as I expected.

Is there any other configuration I need to set before it work?

Any help would appreciated.

View 4 Replies View Related

Bcp Command:

May 8, 2008

im using bcp to export data from MyTable to MyTable.bcp file

the command is in a batchfile, ExportData.bat which i invoke from the command prompt.

ExportData.bat:

bcp MyDB.Dbo.MyTable out MyTable.bcp -N -U<user> -P<password> -S<Server>

is there any method to retrieve the number of rows exported by bcp ommand?
(apart from the messages printed in the command prompt)

View 2 Replies View Related

Command

Apr 14, 2008

what is the command to check whether the sql server is running 32 bit or 64 bit ?

View 4 Replies View Related

Run Command

Apr 14, 2008

using server 2000

is it possible to run a command from tsql. the same as if i hit start>run>command and then entered my command and hit return?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved