Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Adding String To Database, But Name Of String Is Added, Not Data


Hello, I am tring to add a string my database.  Info is added, but it is the name of the string, not the data contained within.  What am I doing wrong?  The text "Company" and "currentUserID" is showing up in my database, but I need the info contained within the string.  All help is appreciated!

 

 

Imports System.Data

Imports System.Data.Common

Imports System.Data.SqlClientPartial Class _DefaultInherits System.Web.UI.Page

 

Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.CreatedUser

'Database ConnectionDim con As New SqlConnection("Data Source = .SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|ASPNETDB.mdf;user instance=true")

'First Command DataDim Company As String = ((CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Company"), TextBox)).Text)

Dim insertSQL1 As StringDim currentUserID As String = ((CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox)).Text)

insertSQL1 = "INSERT INTO Company (CompanyName, UserID) VALUES ('Company', 'currentUserID')"Dim cmd1 As New SqlCommand(insertSQL1, con)

'2nd Command Data

Dim selectSQL As String

selectSQL = "SELECT companyKey FROM Company WHERE UserID = 'currentUserID'"Dim cmd2 As New SqlCommand(selectSQL, con)

Dim reader As SqlDataReader

'3rd Command Data

Dim insertSQL2 As String

insertSQL2 = "INSERT INTO Company_Membership (CompanyKey, UserID) VALUES ('CompanyKey', 'currentUserID')"Dim cmd3 As New SqlCommand(insertSQL2, con)

'First CommandDim added As Integer = 0

Try

con.Open()

added = cmd1.ExecuteNonQuery()

lblResults.Text = added.ToString() & " records inserted."Catch err As Exception

lblResults.Text = "Error inserting record."

lblResults.Text &= err.Message

Finally

con.Close()

End Try

'2nd Command

Try

con.Open()

reader = cmd2.ExecuteReader()Do While reader.Read()

Dim CompanyKey = reader("CompanyKey").ToString()

Loop

reader.Close()Catch err As Exception

lbl1Results.Text = "Error selecting record."

lbl1Results.Text &= err.Message

Finally

con.Close()

End Try

'3rd Command

Try

con.Open()

added = cmd3.ExecuteNonQuery()

lbl2Results.Text = added.ToString() & " records inserted."Catch err As Exception

lbl2Results.Text = "Error inserting record."

lbl2Results.Text &= err.Message

Finally

con.Close()End Try

 

 

 End Sub

End Class




View Complete Forum Thread with Replies

Related Forum Messages:
Only One Character Added To Database Instread Of Full Data String??
When I execute this, it works ok but only one the first character of the request.form["d"] is stored to the db.I checked the sproc with another routine and it adds full data, and I've verified that value of request.form["d"] is longer than one chaacter by printing it to the page. Anyone got any ideas why only the first char is getting added to the db??  SqlConnection SqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
SqlCommand SqlCommand1 = new SqlCommand("addRoute", SqlConnection1);
SqlCommand1.CommandType = CommandType.StoredProcedure;
SqlParameter SqlParameter1 = SqlCommand1.Parameters.Add("@ReturnValue", SqlDbType.Int);
SqlParameter1.Direction = ParameterDirection.ReturnValue;
SqlCommand1.Parameters.Add("@xmlData", Request.Form["d"]);
SqlConnection1.Open();
SqlCommand1.ExecuteNonQuery();
Response.Write(SqlCommand1.Parameters["@ReturnValue"].Value);
//Response.Write(Request.Form["d"]);  

View Replies !
Adding Data To A String
Hi,

I'm not a programmer by trade, so please be gentle with me! I am trying to add or insert data to the beginning of an existing string of data. The string is in one field in a table, with various options seperated by [ ].
An example of the current data is:
[Eye Color:TEST][Hair Color:TEST]
and I would like to add the data [# Persons:1] to the beginning of the string so it looks like this:
[# Persons:1][Eye Color:TEST][Hair Color:TEST]

Can anyone help me with the best way to do this?

View Replies !
Employing XML Formatted String Data Rather Than Normal String(char(), Nchar() Or Varchar() Values
Hello,
Is there a way of passing in an xml formatted string or text to the report through a data set and have the textbox or table in which it displays keep the formatting specified in the xml string rather than in the textbox properties?
 
Thanks.

View Replies !
String Or Binary Data Would Be Truncated. (only For 1700 Character String?)
I am trying to insert a row into a table of Microsoft SQL Server 2000.

There are various columns.















[SNO] [numeric](3, 0) NOT NULL ,
[DATT] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[DATTA] [char] (3000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[CODECS] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,

The [DATTA] column is causing a problem. Even if I am trying to put only 1700 character string into [DATTA], the java code throws the following exception:-



StaleConnecti A CONM7007I: Mapping the following
SQLException, with ErrorCode 0 and SQLState 08S01, to a
StaleConnectionException: java.sql.SQLException: [Microsoft][SQLServer 2000
Driver for JDBC]Connection reset

      at
com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)


Why is it throwing an exception even though the sum-total of this row doesn't exceed 8000 characters?

Can anyone please tell me what's wrong?

View Replies !
Searching For Any Data String In Database
hihere is a problem:i have a databes with many, many tablesthe problem is that i dont know where 'abcd' string is (but it is for surein one of that table)is there any SELECT that could help me with finding this string in database?--greets

View Replies !
Reading Data From A String Into A SQL Database
Hi, i'm writing a SOCKET Port Listener for a Database, it must be multi-threaded and listen on a port for a record that when it comes in, it must write the record to the SQL database (MS SQL Server). I've got the listener to read the data over the port already and write the record into a string which i have already sliced up. Now i need to create a connection to the database and insert the variables into the database.

If Someone will please be able to give me a rough idea of how i could accomplish this with some sample code, then i will be greatful, i'm new to C#, but here is my code that i have so far.

//This is the Connection that i have made and where i am currently stuck, i dunno how to go further. Any help will be welcome.

 public class ConnectionToMSDatabase
 {
      public void InsertDataIntoDatabase(string TableName, string connectionString, string        dataFields)
        {
            string InsertSQLStatement;
            InsertSQLStatement = "INSERT INTO " + TableName + " VALUES (" + dataFields + ")";

                OleDbConnection ConnectionToDatabase = new           OleDbConnection(connectionString);
                ConnectionToDatabase.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = ConnectionToDatabase;
                command.CommandText = InsertSQLStatement;
                command.ExecuteNonQuery();
                command.Connection.Close();
         }
    }


//Here is my connection string, all the retrieved data is stored in a string array call fullRecord

ConnectionStringToDatabase = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;User ID=" +
                                    "Administrator" + ";Initial Catalog=FORGE;Data Source=FORGE";

View Replies !
Adding Apostrophe In A String
I would like to add an apostrophe in a string. eg. The boy's shoes.
Everytime I insert the record, the apostrophe gets drop. eg. The boys shoes.

Any suggestions??

Thanks, Vic

View Replies !
Adding A Leading Character To A String
I'm looking for a string function (or any other quick way) for adding a leading zero to make a string two characters long. For example, if the input is '12' the result will be '12' but if the input is '1', the result will be '01'.

It's actually about making a month number two characters long but I've understood there is no way to make Datediff() to fix it for me.

I thought there might be a string function for this, like there is in many programming languages, but I can't find anything in BOL. I want to keep it simple, because it will be used in a Select and a Group By for aggregating data based on time intervals (year + month).

And, I assume I can't make Datepart() to return year + month directly, only one of the parts at a time.

View Replies !
ADDING COMMENTS IN A SINGLE STRING
Hello,
I would like to know if it is possible to add comments from different columns from table in sql into a single column. Please, see the attached table. I want all comments to be in one column. The outcome should be:
CONFIRMED NEED TO CONFIRM SIGNER AT <CR><LF> received e-mail:<CR><LF> Called Imran again today to see if .



Ideally, I would like to receive all comments in a single string of characters, perhaps separating the comments by <CR><LF>

Here is the table. Sorry my table doesnt look good, but it has the following fields: DATE, LEXNEX_DECISION, COMMENT

DATE LEXNEX_DECISIONCOMMENT
4/3/2007COMPLETECONFIRMED NEED TO CONFIRM SIGNER AT 4/3/2007COMPLETEreceived e-mail:
4/3/2007COMPLETECalled Imran again today to see if .

Help!

View Replies !
Help: About Ms Sql Query, How Can I Check If A Part String Exists In A String?
Hello to all,
I have a problem with ms sql query. I hope that somebody can help me. 
i have a table "Relationships". There are two Fields (IDMember und RelationshipIDs) in this table. IDMember is the Owner ID (type: integer) und RelationshipIDs saves all partners of this Owner ( type: varchar(1000)).  Example Datas for Table Relationships:                               IDMember     Relationships              .
                                                                                                                3387            (2345, 2388,4567,....)
                                                                                                                4567           (8990, 7865, 3387...)
i wirte a query to check if there is Relationship between two members.
Query: 
Declare @IDM int; Declare @IDO int; Set @IDM = 3387, @IDO = 4567;
select *
from Relationship where (IDMember = @IDM) and ( cast(@ID0 as char(100)) in
(select Relationship .[RelationshipIDs] from Relationship where IDMember = @IDM))
 
But I get nothing by this query.
Can Someone tell me where is the problem? Thanks
 
Best Regards
Pinsha

View Replies !
Capitalize A Text String/String Function Related
Hi Folks:

How can I capitalize a string like 'JOHN DOE' into
'John Doe' with one SQL statement. SQL does provide
string function like LOWER(char_expr) which would
change the whole text string to 'john doe' and I don't
want that.
So far, in order to do that, I have to use a front-end
development language like 'Omnis' which has a
string function 'cap()' to capitalize the whole string,
then update the back-end SQL with the new string.
Thank you in advance for your time and advice.

David Nguyen

View Replies !
Need Help With String Manipulation - Splitting 1 String Into Multiple Columns
Hello All,

I'm a non-programmer and an SQL newbie.  I'm trying to create a printer usage report using LogParser and SQL database.  I managed to export data from the print server's event log into a table in an SQL2005 database. 

There are 3 main columns in the table (PrintJob) - Server (the print server name), TimeWritten (timestamp of each print job), String (eventlog message containing all the info I need).  My problem is I need to split the String column which is a varchar(255) delimited by | (pipe).  Example:

2|Microsoft Word - ราย�ารรับ.doc|Sukanlaya|HMb1_SD_LJ2420|IP_192.10.1.53|82720|1

The first value is the job number, which I don't need.  The second value is the printed document name.  The third value is the owner of the printed document.  The fourth value is the printer name.  The fifth value is the printer port, which I don't need.  The sixth value is the size in bytes of the printed document, which I don't need.  The seventh value is the number of page(s) printed.

How I can copy data in this table (PrintJob) into another table (PrinterUsage) and split the String column into 4 columns (Document, Owner, Printer, Pages) along with the Server and TimeWritten columns in the destination table?

In Excel, I would use combination of FIND(text_to_be_found, within_text, start_num) and MID(text, start_num, num_char).  But CHARINDEX() in T-SQL only starts from the beginning of the string, right?  I've been looking at some of the user-defind-function's and I can't find anything like Excel's FIND(). 

Or if anyone can think of a better "native" way to do this in T-SQL, I've be very grateful for the help or suggestion.

Thanks a bunch in advance,

Chutikorn

 

View Replies !
Input String -&> Table -&> Output String?
I have a nasty situation in SQL Server 7.0. I have a table, in whichone column contains a string-delimited list of IDs pointing to anothertable, called "Ratings" (Ratings is small, containing less than tenvalues, but is subject to change.) For example:[ratingID/descr]1/Bronze2/Silver3/Gold4/PlatinumWhen I record rows in my table, they look something like this:[uniqueid/ratingIDs/etc...]1/2, 4/...2/null/...3/1, 2, 3/...My dilemma is that I can't efficiently read rows in my table, match thestring of ratingIDs with the values in the Ratings table, and returnthat in a reasonable fashion to my jsp. My current stored proceduredoes the following:1) Query my table with the specified criteria, returning ratingIDs as acolumn2) Split the tokens in ratingIDs into a table3) Join this small table with the Ratings table4) Use a CURSOR to iterate through the rows and append it to a string5) Return the string.My query then returns...1/"Silver, Platinum"2/""3/"Bronze, Silver, Gold"And is easy to output.This is super SLOW! Queries on ~100 rows that took <1 sec now take 12secs. Should I:a) Create a junction table to store the IDs initially (I didn't thinkthis would be necessary because the Ratings table has so few values)b) Create a stored procedure that does a "SELECT * FROM Ratings," putthe ratings in a hashtable/map, and match the values up in Java, sinceJava is better for string manipulation?c) Search for alternate SQL syntax, although I don't believe there isanything useful for this problem pre-SQL Server 2005.Thanks!Adam

View Replies !
Find In String And Return Part Of String
I am trying to find a way to find a certian character in a string and then select everything after that character.

for example i would look for the position of the underscore and then need to return everthing after it so in this case

yes_no

i would return no

View Replies !
What Is The Purpose Of Adding Term &&" Application Name&&" Into Connection String
 

     for example : " server={0};database={1};trusted_connection=true;application name={3}"
 
 The article  SqlConnection.ConnectionString Property refer this term,but  doesn't specify  use.
 
I want to know whether it will affect sql server and how to find its effect
 
 
 
   thanks

View Replies !
Procedure Or Query To Make A Comma-separated String From One Table And Update Another Table's Field With This String.
We have the following two tables :

Link  ( GroupID int , MemberID int )
Member ( MemberID int , MemberName varchar(50), GroupID varchar(255) )

The Link table contains the records showing which Member is in which Group. One particular Member can be in
multiple Groups and also a particular Group may have multiple Members.

The Member table contains the Member's ID, Member's Name, and a Group ID field (that will contains comma-separated
Groups ID, showing in which Groups the particular Member is in).

We have the Link table ready, and the Member table' with first two fields is also ready. What we have to do now is to
fill the GroupID field of the Member table, from the Link Table.

For instance,

Read all the GroupID field from the Link table against a MemberID, make a comma-separated string of the GroupID,
then update the GroupID field of the corresponding Member in the Member table.

Please help me with a sql query or procedures that will do this job. I am using SQL SERVER 2000.

View Replies !
Converting String To Unicode String In T-SQL
Hi,We have stored proc name proc_test(str nvarchar(30)). So far this prochas been invoked from a .NET application assuming that only Englishcharacter strings will be passed to it. The calls are likeproc_test('XYZ')We now have a requirement for passing Chinese strings as well. Ratherthan changing the calls throughout the application, we would like tohandle it in the stored procedure so that it treats the string as aunicode string. Can we apply some function to the parameter to convertit to unicode so that we don't have to call with an N prefixed to thestring?Thanks,Yash

View Replies !
Ntext Over 4000 Chars Causes 'Data In Row (n) Was Not Update... String Or Binary Data Would Be Truncated...'
When I enter over 4000 chars in any ntext field in my SQL Server 2005 database (directly in the database and through the application) I get an error saying that the data could not be updated because string or binary data would be truncated.Has anyone ever seen this? I cannot figure out what is causing it, ntext should be able to hold a lot more data that this...

View Replies !
Data Conversion From String To Decimal When Saving Data To SQL Server 2005 Using An ADO Recordset
Hello,
 
I am wondering what conversion rules apply, when a string, which contains a number, is saved to a SQL Server 2005 into a column of type decimal.
 
This is the code I€™m using (C++):
 
CString cValue = "0.75"
_variant_t vtFieldValue;
vtFieldValue = _variant_t(cValue)
pRecordSet->Fields->Item["MyColumn"]->Value = vtFieldValue;
 
"pRecordSet" is an ADO recordset. The database column "MyColumn" is of type "decimal(19,10)".
 
The most important question for me is, if the regional settings of the database server or the regional settings of the client PC are considered during the conversion from the string to the decimal value. For example in standard French regional settings the "." would not be recognized as decimal separator.
 
I am also wondering if the language of the database instance, in which this data is saved, is considered during this conversion or any other settings of this database instance.
 
So my general question is: Does anybody know exactly what rules apply during the above mentioned conversion?
 
Thank you for your help.
 
Regards,
Volker
 

View Replies !
Truncation Of String Data With Data Reader Source Connecting To ODBC DSN
A data reader is using a connection manager to connect to an ODBC System DSN .  A query in the SqlCommand property is provided.   Data is being truncated in the only string column .  The data type in data reader output-->external columns shows as Unicode string [DT_WSTR] Length 7. 

The truncated output in a text file is the first 3 characters from left to right .  Changing the column order has no effect.

 

A linked server was created in SQL Server Management Studio to test the ODBC System DSN using the following:

EXEC sp_addlinkedserver
   @server = 'server_name',
   @srvproduct = '',
   @provider = 'MSDASQL',
   @datasrc = 'odbc_dsn_name'

Data returned using "OPENQUERY" does not truncate the string column indicating that the ODBC Driver returns data as expected with sql 2005, but not with the Data Reader. 

Any assistance would be appreciated. 

Thanks,

View Replies !
Import Data From Excel-Sheet Via OleDb In VB.Net - How To Get A Columns Data As String?
 Hello,

i want to import data from an excel sheet into a database. While reading from the excel sheet OleDb automatically guesses the Datatype of each column. My Problem is the first A Column which contains ~240 Lines. 210 Lines are Numbers, the latter 30 do contain strings. When i use this code:



 



Code BlockDim sConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & conf_path_current & file_to_import & ";Extended Properties=""Excel 8.0;HDR=NO"""
Dim oConn As New OleDb.OleDbConnection(sConn)
Dim cmd1 As New System.Data.OleDb.OleDbCommand("Select * From [Table$]", oConn)
Dim rdr As OleDb.OleDbDataReader = cmd1.ExecuteReader
Do While rdr.Read()
Console.WriteLine(rdr.Item(0)) 'or rdr(0).ToString
Next
 
 


it will continue to read the stuff till the String-Lines are coming.
when using Item(0), it just crashes for trying to convert a DBNull to a String, when using rdr(0).ToString() it just gives me no value.

So my question is how to tell OleDB that i want that column to be completly read as String/Varchar?

Thanks for Reading

- Pierre from Berlin

 
[seems i got redirected into the wrong forum, please move into the correct one]

View Replies !
String Data To Int
I'm trying to import a student id in one database (nvarchar(7)) to int in another database. No sure whether I need ato use cast or convert. Anyone have some examples?

View Replies !
String Or Binary Data Would Be Truncated. I Get This Error When Entering Data Using Sql Server Management Studio Express.
String or binary data would be truncated.  I get this error when entering data using sql server management studio express.
 
I am not running a sql to insert or update the table.  This is through the EDI.
 
The data type is varchar(100).  I enter one character and it errors on me.  So this isn't a string being too long problem.
 
Any ideas?
 
 
 
 

View Replies !
TSQL - Trim String Containing Both Data And Value Into 2 Separate Data Fields
Hi!
Need help with this one:
I have a column with a string composed by several data.  After using REPLACE several times, I get something like the data below, which has (in most of cases) a value and a date.
 







 378  9/05

 388  9/05

 4/05

 1/06 606  

 1/06 646  

 76 5/05 

 100 1/05 

 118 8/05 

 129 8/05 

  9/05  342 

 05/3 123 

 1/07

 4/06 164 
The problem is that I need to get each value alone (to separate columns), in example:
Value          Date
378             09/2005
388             09/2005
0                 04/2005
...
606              01/2006
 
and so on...
In addittion you can see that sometimes the Value come first or alone, and sometimes the Date come first  or alone.
 
I will appreciate any good ideas,
Thanks in advance,
Aldo.
 
 
 

View Replies !
Modify String Data Base On Data In The Table
I need to get rid of the first char of data in a field f1 (in sql server)

I tried to use:

update myTable
set f1= substring(f1,1,f1.Len -1)

and get error "The column prefix 'f1' does not match with a table name or alias name used in the query.

Could anyone help? Thanks.

View Replies !
Summarizing Data And Building A String With Summarized Data
Hi there,
 
I'm faced with a bit of an issue within SSIS and I was wondering if anyone could help. I have data that looks like the following:
 
TABLE 1:::
CustomerID       StaffID             Percentage
A123                 1234                1
A124                 1245                1
A125                 1234                0.7
A125                 1443                0.3
B117                 6653                1
B154                 8899                1
C776                 1443                0.2
C776                 1337                0.6
C776                 1245                0.2

 
I need to be able to summarize the data above and build up a string that should look like the following:
 
TABLE 2:::
CustomerID       StringID
A123                 1234||1
A124                 1245||1
A125                 1234||0.7||1443||0.3
B117                 6653||1
B154                 8899||1
C776                 1443||0.2||1337||0.6||1245||0.2
 

As you can see in Table 1, if a CustomerID has only one StaffID associated to it, the "Percentage" Column's value is 1. In the cases where there is more than one StaffID associated to a particular CustomerID, the percentage column get's split up among the StaffIDs, however the sum of this split can never exceed 1 (100%) per CustomerID.
 
I need to know how to find the cases where there is more than one StaffID associated to a CustomerID, group the CustomerIDs, and build a string made up with the StaffID and Percentages as shown in Table 2.
 
Any help would be greatly appreciated, as I've struggled with this one for a while and have hit a brick wall.
 
Ciao,
Colin

View Replies !
SQL String Data Parsing
<p>
Hi everybody, I was hoping to get some advice something I can't quite get my head around.  I have a SQL db which contains a table with ratings using the AJAX rating control.
When someone rates an object, I need to select the current rating and then use those numbers to;
- calculate the new average
- add new score to total score
- increment number of votes by one.
 
I thought this can be best achieved using the SELECT statement and then parsing the SELECT string. (is the string comma separated?)
using each array, i'd need to convert this into integers and then do the calculation. and re-upload the data to the ratings table (using the UPDATE statement).
 
Is this the best way of proceeding?  I have tried initially to write the code using three sql statements. But that would mean to many requests from the server, right?
Below is the conde I have writting already.int myrating;
myrating = Rating1.CurrentRating;string getscore = "SELECT " +
"RatingScore" +"FROM Rating " +
"WHERE ItemID= '" + _ItemID+ "'";string getcount = "SELECT " +
"RatingCount" +"FROM Rating " +
"WHERE ItemID = '" + _ItemID + "'";string getaverage = "SELECT " +
"RatingAverage " +"FROM Rating " +"WHERE ItemID = '" + _ItemID + "'";
 
int _ratingscore;int _newscore; _ratingscore = int.Parse(getscore);
_newscore = _ratingscore + myrating; //add new rating score to old scoreint _ratingcount;
int _newcount;_ratingcount = int.Parse(getcount);
_newcount = _ratingcount + 1; //increase count by 1int _ratingaverage;
int _newaverage;_ratingaverage = int.Parse(getaverage);
_newaverage = _newscore / _newcount; //calculate new average rating
 otherwise
 otherwise would i be best off to do the following?...
string[] dbRatings = SQLstring.Split(',');
 ??
Any help would be appreciated.
Many thanks in advance.
Phil
 
</p>

View Replies !
Getting Data To A String From A SQL Server
Hey guys :) First, im sorry for my English - I'm really trying! :D I started using ASP.NET with Visual Web Developer for about 2 weeks ago, so im still very new to it. Before the I started with ASP.NET, I used classic ASP and now I really miss it :DMy problem is that I'm trying to make my own login-system. Creating users with detailsView to my SQLServer is very simple, but generating the login system is a bit harder I think. In the old days I would just make a recordset and the do something like If (rs.BOF or rs.EOF) then bla bla bla and the but the username or userID into a Session, but that seems to not be the way to do it in ASP.NET/Visual Basic?How do I do?Really just wanna know where to start :)Thanks :)/Hovgaard - Denmark

View Replies !
Large String Data
I have a web site that allows user to enter large strings into a database (comments, etc). What is the best way to do that? Right now I have them limited to 25 characters and the data type is varchar. Is there a better way?

Thanks!

View Replies !
String Data, Right Truncation
I'm trying to write a large amount of text (approx 700 chars) to a field with datatype text from a Visual Basic app. I call a stored procedure to insert the line of data, consisting of a customerID (int) and the text data. However, I continualy get the message ODBC SQL Server Drive String Data Right Truncation.

Can anyone help??

Any assistance GREATLY appreciated

Thanks

View Replies !
Converting Hex Data To String
I am writing a stored procedure that generates a computername for new workstations. Our naming standards, based on terminal ID's, are as follows:
'R' + X + Y + ZZZ, where 'R' is the letter 'R', X is a hex digit indication a locatoin, Y is a hex digit indicating business line, and ZZZ is a hexadecimal sequential number assigned within each location/busines line, for up to 4096. (This isn't a perfect naming standard, but is an improvement over the one that preceded it and is a requirement for our legacy applications).
I can do everything fine, and calculate the sequential number using an int. Once I have the new number, I am trying to convert the integer to a varbinary, then convert that to a string, then use RIGHT to get the rightmost three characters of the hex string.
set @SEQNUM = 4095
set @HEXSEQNUM = CONVERT(varbinary ,@SEQNUM)
PRINT CONVERT(varbinary ,@SEQNUM) -- displays 0x00000FFE etc.
PRINT 'HEXSEQNUM ' + @HEXSEQNUM -- displays 'HEXSEQNUM'


Any ideas? I am very new to TSQL...

View Replies !
String Data, Right Truncation
Hi,

I am trying to execute one huge select statement from my application using ODBC, but I am getting this error:

[Microsoft][ODBC SQL Server Driver]String data, right truncation.

the select statement is bigger than 2000 characters, but I don't have any long string column, just strings and numbers. How can I work around this?

Is there any max size? Because if I use less than 1000 characters, it works fine.

I am using Centura/SqlWindows, Native Sql Server ODBC and SqlServer 2005. unfortunately, I can not use Ole from my application.

cheers,

Alessandro Camargo

View Replies !
Help With Retrieving String Data
Hello,
 
I am trying to retrieve only the first few characters (12 to be precise) from this string that is coming in from FoxPro to SQL Server 2005 and I am coding in C#.  I have tried these methods (after reading it in a book, as I am new to this) but it still gives me an error saying that the field cannot exceed 12 characters. 
 
autoClaimSalvage.Phone = "Select LEFT ('" + (string)(drInputDataSource["OWNPHN"]) + "',12) From '" + entityManager.TargetTable + "'";
autoClaimSalvage.Phone = "Select LTRIM(RTRIM(OWNPHN)) From '" + entityManager.TargetTable + "'";
autoClaimSalvage.Phone = "Select LTRIM(RTRIM('" + ((string)(drInputDataSource["OWNPHN"])) + "'))" + entityManager.TargetTable + "'";

 
Please let me know what i am doing wrong and if anyone has a sample code or if you can point me in the right direction, I will appreciate it.
 
Thanks for your help in advance.

View Replies !
DB Connection String And Getting Data
 

Hi, Folks,

Can we have a table listing the BEST solution of DB Connection string

and getting data for each version of framework and databses?

use Oledb? SQlConnection? ODBC? what's the BEST solution?

 

                                    Oracle                 |                 MS SQL  

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

Framework 1.0                 ?                   |                      ?

Framework 1.1                 ?                   |                      ?

Framework 2.0                  ?                  |                      ?

thanks alot

Please have some code for the ?

 

View Replies !
Select Data From String
I am trying to extract the numbers only from a string field any help would be great.

field is phone number (123)123-2584 and need to display 1231232584
thanks

View Replies !
String Data Issue.
Hi all

I have a column with the following data

Change Order 1887:MODIFIED EXPIRE_DATE TO 2007-10-26 00:00:00.000

Now i need to get only 2007-10-26 00:00:00.000 from the above string data.

Thanks

View Replies !
Reading Xml Data From A String
Hi,

I want to read xml from a string and save it in SQL. Can anyone help me plz.

Regards,

View Replies !
Database Connection String
Ok I built a web system and for a company that I want to use in my portfolio. But I'm have some trouble getting the connection string for my local machine, also the format of the connection string for my local machine. Its a SQL server DB, how would I go about finding my connection string and what is syntax for the connection string in my asp page?

Thanks in advance.

View Replies !
Search A String Throughout The Database
Hello
I have a Database which contains like 1000 Tables.
I am not the designer of that DB.So I need to in which table and which column
that string exists. IS there a DBWIDE String search possible?
Thanks and Regards

View Replies !
STRING To Database Timestamp
 

Hi i want to convert string to database timestamp
 
 
please tell me i tried derived column it failed
 
 

View Replies !
String Or Binary Data Would Be Truncated.
Hi Guys, I'm trying to save the data into 2 table when i click the button. But it pops out this error: String or binary data would be truncated. The statement has been
terminated. 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.Data.SqlClient.SqlException: String or binary data would be
truncated. The statement has been terminated.Source Error:




Line 116:Line 117: Sqlinsert.Connection.Open()Line 118: Sqlinsert.ExecuteNonQuery()Line 119:Line 120: Sqlinsert.Connection.Close()  I Don't know what it means so i paste my codes regarding the button & the redline   Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'add the data into shopper


Dim strsqlcmd As String

Dim strName, straddress As String
Dim strContact, strEmail, strPw As String
Dim strIC As String


strName = txtName.Text
straddress = txtAdd.Text
strEmail = txtEmail.Text
strContact = txtboxContact.Text
strIC = txtIC.Text


strsqlcmd = "Insert Into Shopper (Name, Address, Contact, Email, IC) Values (@Name, @Address, @Contact, @Email, @IC)"

SqlCommand1.CommandText = strsqlcmd
With SqlCommand1.Parameters
.Add("@Name", strName)
.Add("@Address", straddress)
.Add("@Contact", strContact)
.Add("@Email", strEmail)
.Add("@IC", strIC)
End With
SqlCnt.Open()

SqlCommand1.ExecuteNonQuery()

SqlCnt.Close()

'add the data into the presc


strsqlcmd = "Insert Into Prescription (Name, Address, Contact, Email, IC) Values (@Name, @Address, @Contact, @Email, @IC)"

Sqlinsert.CommandText = strsqlcmd
With Sqlinsert.Parameters
.Add("@Name", strName)
.Add("@Address", straddress)
.Add("@Contact", strContact)
.Add("@Email", strEmail)
.Add("@IC", strIC)
End With

Sqlinsert.Connection.Open()
Sqlinsert.ExecuteNonQuery()

Sqlinsert.Connection.Close()


' go the add item
Response.Redirect("NewPrescItem.aspx")  why my sqlinsert.excutenonquery will have this error? and what is this error really means? Thanks in advance 

View Replies !
String Or Binary Data Would Be Truncated.
 Hi,I am getting the following error:System.Data.SqlClient.SqlException: String or binary data would be
truncated.The statement has been terminated.Can someone tell me what it means?Thanks,Jon 

View Replies !
String Or Binary Data Would Be Truncated.
I keep getting the error "String or binary data would be truncated." when I try to insert data into SQL Sever 2005 from an ASP.net page.  Having searched thoughout the web, I know this is generally caused because one of the values being inserted is bigger than the size of the field it's going into.  But, I have tested this out in many different ways, and this is not what's causing the problem.
I have tried doing the insert as a SQL statement and using the "ExecuteNonQuery" command.  I have also tried running this through a stored procedure.  Neither works.  In both situations, I have captured the TSQL statements via SQL Profiler and run them in a query window.  In both cases, the statements work just fine in a query window.
When I try to do the insert via a stored procedure, all of the statements in the stored procedure show up in SQL Profiler, including the final SELECT statement I have the indicates a successful result.  But, the data does not end up in the table and the ASP.net page returns an error.
Also, I have run both the Stored Proceure and the SQL insert statement making all of the fields blank as a way of ensuring that no value can be longer than a field's size.  But, in both cases I still get the same error.
Here's the line I use when doing a regular insert:
Dim Command4 = New Data.SqlClient.SqlCommand("INSERT INTO ResourceCenter(UserEmail, UserPassword, Region, FirstName, LastName, Company, JobTitle, Address1, Address2, City, StateProvince, ZipPostalCode, Country, BusinessPhone, WebSiteURL, HowDidYouFind, Industry, WhatTypeOfSolution, CompanySize, NumLogins, LastLogin) VALUES ('" & UserEmail & "', '" & UserPassword & "', '" & Region & "', '" & FirstName & "', '" & LastName & "', '" & Company & "', '" & JobTitle & "', '" & Address1 & "', '" & Address2 & "', '" & City & "', '" & StateProvince & "', '" & ZipPostalCode & "', '" & Country & "', '" & BusinessPhone & "', '" & WebSiteURL & "', '" & HowDidYouFind & "', '" & Industry & "', '', '', 1, " & Now & ")", conn2)
Dim NumRowsUpdated2 = Command4.ExecuteNonQuery()
Here's my code when I call a stored procedure:
Dim dsSignup As New Data.DataSet()Dim Command4 As New Data.SqlClient.SqlDataAdapter("ap_ResourceCenterModify", conn2)Command4.SelectCommand.CommandType = Data.CommandType.StoredProcedureCommand4.SelectCommand.Parameters.Add("@UserID", Data.SqlDbType.Int, 0).Value = 0Command4.SelectCommand.Parameters.Add("@UserEmail", Data.SqlDbType.VarChar, 100).Value = UserEmailCommand4.SelectCommand.Parameters.Add("@UserPassword", Data.SqlDbType.VarChar, 20).Value = UserPasswordCommand4.SelectCommand.Parameters.Add("@Region", Data.SqlDbType.VarChar, 50).Value = RegionCommand4.SelectCommand.Parameters.Add("@FirstName", Data.SqlDbType.VarChar, 100).Value = FirstNameCommand4.SelectCommand.Parameters.Add("@LastName", Data.SqlDbType.VarChar, 100).Value = LastNameCommand4.SelectCommand.Parameters.Add("@Company", Data.SqlDbType.VarChar, 100).Value = CompanyCommand4.SelectCommand.Parameters.Add("@JobTitle", Data.SqlDbType.VarChar, 100).Value = JobTitleCommand4.SelectCommand.Parameters.Add("@Address1", Data.SqlDbType.VarChar, 100).Value = Address1Command4.SelectCommand.Parameters.Add("@Address2", Data.SqlDbType.VarChar, 100).Value = Address2Command4.SelectCommand.Parameters.Add("@City", Data.SqlDbType.VarChar, 100).Value = CityCommand4.SelectCommand.Parameters.Add("@StateProvince", Data.SqlDbType.VarChar, 50).Value = StateProvinceCommand4.SelectCommand.Parameters.Add("@ZipPostalCode", Data.SqlDbType.VarChar, 50).Value = ZipPostalCodeCommand4.SelectCommand.Parameters.Add("@Country", Data.SqlDbType.VarChar, 200).Value = CountryCommand4.SelectCommand.Parameters.Add("@BusinessPhone", Data.SqlDbType.VarChar, 100).Value = BusinessPhoneCommand4.SelectCommand.Parameters.Add("@WebSiteURL", Data.SqlDbType.VarChar, 200).Value = WebSiteURLCommand4.SelectCommand.Parameters.Add("@HowDidYouFind", Data.SqlDbType.VarChar, 100).Value = HowDidYouFindCommand4.SelectCommand.Parameters.Add("@Industry", Data.SqlDbType.VarChar, 100).Value = IndustryCommand4.SelectCommand.Parameters.Add("@WhatTypeOfSolution", Data.SqlDbType.VarChar, 250).Value = WhatTypeOfSolutionCommand4.SelectCommand.Parameters.Add("@CompanySize", Data.SqlDbType.VarChar, 100).Value = CompanySizeCommand4.Fill(dsSignup)Any ideas of what else I can try?  Thanks in advance.

View Replies !
String Or Binary Data Would Be Truncated
I am currently developing a simple program that will upload ms-word documents to a database so users can view them within the department.
The program worked prefectly while using sql 2005 with the these fields:
FormId            intFileName        nvarchar(50)FileBytes        varbinary(Max)
This was done in unit testing, now in system testing there is a difference.
A slight downgrade in the database and server software!
We are using sql 2000 on a 2000 server and the FileBytes datatype had to change to the following:
FormId           intFileName       nvarchar       50 FileBytes       varbinary      8000
There is no 'Max' option in sql 2000 for the datatype varbinary. 
So when the insert is perform, we get this error message:
 String or binary data would be truncated.The statement has been terminated.
I am guessing it has something to do with FileBytes, because this is the only thing that changed.
I just don't know how to solve the problem.P.S.The application is in ASP.NET 2.0
 
Thanks,
xyz789
 
 
 
 

View Replies !
Data Conversion (String To DateTime)
I am trying to insert data from a web form to a SQL Database.  I am receiving the following error: {"String was not recognized as a valid Boolean."}  I am also receiving a similar error for text boxes that have dates. 
 Below is the code that I am using:
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:ConnMktProjReq %>"
selectcommand="SELECT LoanRepName,Branch,CurrentDate,ReqDueDate,ProofByEmail,ProofByEmail,FaxNumber,ProjectExplanation,PrintQuantity,PDFDisc,PDFEmail,LoanRepEmail FROM MktProjReq"
insertcommand="INSERT INTO MktProjReq(LoanRepName, Branch, CurrentDate, ReqDueDate, ProofByEmail, ProofByEmail, FaxNumber, ProjectExplanation, PrintQuantity, PDFDisc, PDFEmail, LoanRepEmail) VALUES (@RepName, @BranchName, @Date, @DueDate, @ByEmail, @ByFax, @Fax, @ProjExp, @PrintQty, @Disc, @Email, @RepEmail)">
<InsertParameters>
<asp:FormParameter Name="RepName" FormField="LoanRepNameBox"/>
<asp:FormParameter Name="BranchName" FormField="BranchList"/>
<asp:FormParameter Name="Date" FormField="CurrentDateBox" Type="DateTime"/>
<asp:FormParameter Name="DueDate" FormField="ReqDueDateBox" Type="DateTime"/>
<asp:FormParameter Name="ByEmail" FormField="ProofByEmailCheckbox" Type="boolean"/>
<asp:FormParameter Name="ByFax" FormField="ProofByFaxCheckbox" Type="boolean"/>
<asp:FormParameter Name="Fax" FormField="FaxNumberBox"/>
<asp:FormParameter Name="ProjExp" FormField="ProjectExplanationBox"/>
<asp:FormParameter Name="PrintQty" FormField="PrintQuantityBox"/>
<asp:FormParameter Name="Disc" FormField="PDFByDiscCheckbox" Type="boolean"/><asp:FormParameter Name="Email" FormField="PDFByFaxCheckbox" Type="boolean"/>
<asp:FormParameter Name="RepEmail" FormField="LoanRepEmailBox"/>
</InsertParameters>
</asp:SqlDataSource>protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSource1.Insert();
}
I have been searching forums for parsing data, but I haven't found anything that works.  Can anyone provide guidance.
Thank you,
Paul

View Replies !
String Or Binary Data Would Be Truncated
Hi Folks,
After I inserted a row in my Database (row 27) I started getting this error when I try to insert, update or delete the record in the database.
I've searched about the error on google and it says that I should have a field that crossed the limit of characters.
I have only the autoincrement field, two varchar fields and a text field, neither one of the varchar fields crossed the limit, they arent even close. I found in google that one solution would be turn the field that is having problems in a text field, but the only field that actually can be causing the problem already is of the text type.
The exact error I get on VS 2005 when trying to change something in the row 27 is:
"No row was updated.
The data in row 27 was not committed.Error Source: .Net SqlClient Data Provider.Error Message: String or binary data would be truncated.The statement has been terminated.
Corret the errors and retry or press ESC to cancel the change(s)."
I need some help guyz, see ya, hugs.

View Replies !
String Or Binary Data Would Be Truncated. :((
Hi all,
when ever i try uploadin the file to the database, i am facing this weird probs :(
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.Data.SqlClient.SqlException: String or binary data would be truncated.Source Error:



Line 124:
Line 125:// Update data source
Line 126:dbAdapt.Update(dbSet,"tblFile1");
Line 127:
Line 128:// Get newFileID
i donno what this means :(
well the code is like this
private void Button1_Click(object sender, System.EventArgs e)
{
HttpPostedFile myFile = filMyFile.PostedFile;
// Get size of uploaded file
nFileLen = myFile.ContentLength;
nFiletype = myFile.ContentType;
// Allocate a buffer for reading of the file
myData = new byte[nFileLen];
// Read uploaded file from the Stream
myFile.InputStream.Read(myData, 0, nFileLen);
strFilename = Path.GetFileName(myFile.FileName);
if( myData.Length != 0)
{
WriteToDB(strFilename,nFiletype,ref myData);
}
}
private int WriteToDB(string strName, string strType, ref byte[] Buffer)
{
int nFileID = 0;
// Create connection
SqlConnection dbConn = new SqlConnection("Data Source=D3BKIRAN; Database=ooc;UID=sa;Password=*****");
// Create Adapter
SqlDataAdapter dbAdapt = new SqlDataAdapter("SELECT * FROM tblFile1", dbConn);


// Create and initialize CommandBuilder
SqlCommandBuilder dbCB = new SqlCommandBuilder(dbAdapt);
// Open Connection
dbConn.Open();

// New DataSet
DataSet dbSet = new DataSet();

// Populate DataSet with data
dbAdapt.Fill(dbSet, "tblFile1");
// Get reference to our table
DataTable dbTable = dbSet.Tables["tblFile1"];
// Create new row
DataRow dbRow = dbTable.NewRow();
// Store data in the row
dbRow["FileName"] = strName;
dbRow["FileSize"] = Buffer.Length;
dbRow["ContentType"] = strType;
dbRow["FileData"] = Buffer;
// Add row back to table
dbTable.Rows.Add(dbRow);
// Update data source
dbAdapt.Update(dbSet,"tblFile1");
// Get newFileID
if( !dbRow.IsNull("FileID") )
nFileID = (int)dbRow["FileID"];

// Close connection
dbConn.Close();
// Return FileID
return nFileID;
}
 
plz any one give me an soln for the same
thanks in advance
 

View Replies !
String Or Binary Data Would Be Truncated
I have a stored proc that inserts binary data into an image field.

I am getting a "String or binary data would be truncated" error when trying to insert large data, but this is *no where* near the maximum size of the image datatype.

Should I be declaring the size of the image parameter in my SQLCommand or something?

TIA,
Mark

Code example:
The sproc:


ALTER PROCEDURE sproc_Content_Insert
(
@ContentName varchar(250),
@ContentDesc varchar(500),
@ContentType varchar(25),
@Content image,
@LocationID int
)
AS
INSERT INTO tbl_Content (ContentName, ContentDesc, ContentType, Content, LocationID)
VALUES (@ContentName, @ContentDesc, @ContentType, @Content, @LocationID)


The method:

Public Sub SaveBinaryContent(ByRef ContentName As String, ByRef ContentDesc As String, ByRef ContentType As String, ByRef Content As String, ByRef LocationID As Integer)

'convert the content to a binary stream.
Dim ms As New System.IO.MemoryStream
Dim bf As New BinaryFormatter
bf.Serialize(ms, Content)
ms.Position = 0


Dim oConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim cmd As New SqlCommand("sproc_Content_Insert", oConn)
With cmd
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@ContentName", ContentName)
.Parameters.Add("@ContentDesc", ContentDesc)
.Parameters.Add("@ContentType", ContentType)
.Parameters.Add("@Content", ms.ToArray)
.Parameters.Add("@LocationID", LocationID)
End With
oConn.Open()
cmd.ExecuteNonQuery()
oConn.Close()
oConn.Dispose()
cmd.Dispose()

bf = Nothing
ms = Nothing

End Sub

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved