SELECT(ing) One DB Column Value Into A String In C#... How?

Jun 18, 2007

hey everyone, everyone here has been extremely helpful, I'm extremely appreciative. i have another question if anyone has the time.
I want to pull the value of one column/row into a string, i know this value to be one int or 1 word under 10 characters. I'd like to be able to use this variable as a conditional, so my if/else statements have information to work off of. I have been using the following format in by code-behind pages to do my SQL insert/update/delete - however I cannot figure out how to SELECT and get those results into a string. I'm new obviously, so dumbed-down explanation would be greatly appreciated!
This is what I've used so far for working with my DB:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlDataSource profilesinsert = new SqlDataSource();
        profilesinsert.ConnectionString = ConfigurationManager.ConnectionStrings["ProfilesConnectionString1"].ToString();
        profilesinsert.InsertCommandType = SqlDataSourceCommandType.Text;
        profilesinsert.InsertCommand = "INSERT INTO ProfileComments  (Approved) VALUES (@Approved)";
        profilesinsert.InsertParameters.Add("Approved", "yes");
        profilesinsert.Insert();
    }
 The SELECT into a string I'd like to do on page_load, so that I can test that variable upon button click, and have a different value in "Approved" depending on the 1 int or small word result from my SELECT.
THANK YOU very much to anyone who offers help! love you guys :) 

View 19 Replies


ADVERTISEMENT

SELECT Part Of A String In A Column

Dec 23, 2013

I'm trying to form a query that will select part of a result.I'm trying to take out the ending of results that end in '-PR'.

Example: The original result is 'Jbbx32-PR'. I want to select it as 'Jbbx32'.

View 5 Replies View Related

Cast/Convert Mmddyy In String To New DB_DATETIMESTAMP Column In Derived Column Transformation

Mar 5, 2007

Hi,
I have dates in "mmddyy" format coming from the sources and they are older dates of mid 80s like 082580 for instance.

When I cast it this way (DT_DBTIMESTAMP) Source_Date , It says ok but throws a runtime error.

When I hardcode a date in same format, (DT_DBTIMESTAMP) "082580" , It becomes red (an indication of syntax error) . Please note that we use double quotes in expressions in Derived Column Transformation; So an anticipation that using double quotes over single ones would be the syntax problem would be wrong.



Any help in this will sincerely be appreciated.


Thanks

View 7 Replies View Related

Is It Possible To Re-reference A Column Alias From A Select Clause In Another Column Of The Same Select Clause?

Jul 20, 2005

Example, suppose you have these 2 tables(NOTE: My example is totally different, but I'm simply trying to setupthe a simpler version, so excuse the bad design; not the point here)CarsSold {CarsSoldID int (primary key)MonthID intDealershipID intNumberCarsSold int}Dealership {DealershipID int, (primary key)SalesTax decimal}so you may have many delearships selling cars the same month, and youwanted a report to sum up totals of all dealerships per month.select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',sum(cs.NumberCarsSold) * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDMy question is, is there a way to achieve something like this:select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',TotalCarsSoldInMonth * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDNotice the only difference is the 3rd column in the select. Myparticular query is performing some crazy math and the only way I knowof how to get it to work is to copy and past the logic which isgetting out way out of hand...Thanks,Dave

View 5 Replies View Related

SELECT Column Aliases: Refer To Alias In Another Column?

Apr 9, 2008

Using SQL Server 2000.  How can I refer to one alias in another column?E.g., (this a contrived example but you get the idea)SELECT time, distance, (distance / time) AS speed, (speed / time) AS acceleration FROM dataNote how the speed alias is used in the definition of acceleration alias but this doesn't seem to work.

View 11 Replies View Related

SELECT Column Aliases: Refer To Alias In Another Column?

Apr 10, 2008

Using SQL Server 2000. How can I refer to one alias in another column?

E.g., (this a contrived example but you get the idea)

SELECT time, distance, (distance / time) AS speed, (speed / time) AS acceleration FROM data

Note how the "speed" alias is used in the definition of "acceleration" alias but this doesn't work.

View 14 Replies View Related

Using Column Number Inplace Of Column Name In SQL Select Statement

Jul 20, 2005

Hello All,Is there a way to run sql select statements with column numbers inplace of column names in SQLServer.Current SQL ==> select AddressId,Name,City from AddressIs this possible ==> select 1,2,5 from AddressThanks in Advance,-Sandeep

View 1 Replies View Related

Select Column Value Which Is Selected From A Column Of Another Table

Jan 2, 2004

i need help to get the value of a column which is selected from a column of another table....

View 3 Replies View Related

Transact SQL :: Select Row With Max (column Value) Group By Another Column

May 19, 2015

i dont't know how to select row with max column value group by another column. I have T-SQL

CREATE PROC GET_USER AS
BEGIN
SELECT T.USER_ID ,MAX(T.START_DATE) AS [Max First Start Date] ,
MAX(T.[Second Start Date]) AS [Max Second Start Date],
T.PC_GRADE,T.FULL_NAME,T.COST_CENTER,T.TYPE_PERSON_NAME,T.TRANSACTION_NAME,T.DEPARTMENT_NAME ,T.BU_NAME,T.BRANCH_NAME,T.POSITION_NAME
FROM (

[code]....

View 3 Replies View Related

Sql Select String Help

Aug 8, 2005

I'm having trouble figuring out how to create the correct select string. My SQL table is like this:tblSoldVehilces   Contract Date   Stock Number      Vin Number   Make   Model   Sale Type     PIDI'm trying to find a SQL string that will return a table that I"m not sure is possible.What I need is to get a table like this:Make   Model   CountMake   Model   CountWhere it will for instance count all the Honda Accords and give me a total in return so that I can graph all the honda accords sold...so on and so fourth.  There is consistancyin the data for model names and such.(ie an Accord is always an Accord and never an accord LX)Any help would be greatly appreciated.  I'll continue to read posts to see if I can find the answer.ThanksJosh

View 2 Replies View Related

' In A Dynamic Select String?

Apr 12, 2005

I'm building a select string on the fly based on criteria selected by the user.  The user is given a data grid with Names and Check Boxes, where they can select multiple names and then either print those selections, or download them to excel.  Everything is working fine, except when the Name has an ' in it.  For example O'Kelly or St. John's.  I know I can take all the 's out of the database, but I'd rather keep the data authentic.  Is there a way to manipulate a select string built on the fly accounting for an embedded '?
For example, I build Select * from table where Name IN ('Smith', 'Jones', 'Jordan', 'Bird', 'O'Kelly').... the ' in O'Kelly ends my string and my sql statement blows up.
Any ideas?
Sample Code:<code>         For Each SelectedIndex In rsc.SelectedIndexes                Counter=Counter + 1                dgAssociates.SelectedIndex = SelectedIndex                If Counter = 1 then                    SelectString = "Select * from Associate_Table where AssociateID IN ('" & dgAssociates.SelectedItem.Cells(16).Text() & "'"                Else                    SelectString &= ",'" & dgAssociates.SelectedItem.Cells(16).Text() & "'"                End If            Next            If Counter > 0 then                SelectString &= ")"            End If</code>

View 2 Replies View Related

Select String Concatenation

Mar 13, 2006

I want to concatanate all text rows returned by the following sql statement:

"SELECT Text FROM PageText WHERE PageTextId = 1"

Table "PageText" has the following columns:
---------------------------------------------
PageTextId (int)
SortOrder (int)
Text (nvarchar(4000))

Is it possible to do this? Kinda like doing a "SUM()" if the values would have been numeric?

View 2 Replies View Related

Select Where String Contains Substring

Oct 17, 2007

i'm using sql server 2005 and i need the sql i can use to select rows where the string contains a substring (in access i used instr but now it tells me it's not a built-in function.

View 4 Replies View Related

Select Data From String

Dec 6, 2007

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 1 Replies View Related

SELECT...LIKE: How To Get '100' String Whithout Getting '45,100'

Jul 20, 2005

HelloWe've got a string field with some words, and I created a formso that anybody could search someting into this field.SELECT * FROM customer_table WHERE description LIKE '%query%'";But if you search '100', it returns '45,100'. Or if you get'plugged', it reurns 'unplugged'.I tried with:SELECT * FROM customer_table WHERE description LIKE '% query %'";(note the blanks after and before)But it does not work with a word in the beginning of the field.Does anybody have any experience? Thank you very much.

View 1 Replies View Related

Select Only Lower Case String

Apr 6, 2007

For example, 
select fieldA form tableA where fieldA = 'aaa'
I got following output
fieldA
---------
aaa
aAa
AAA
AAa
...
if I want select only the lower case 'aaa', how can I do that?
 

View 2 Replies View Related

Using String Variables In SQL Select Statements

Apr 13, 2008

Hi
I am trying to include a string variable in a Select Statement. 
My problem is that when I code with the user name hard coated in the SQL Statement it works fine (see below:)
cmd.CommandText = "SELECT UserPswd, StudioID, StudioCode FROM Users WHERE UserName = 'jdoe' " But when I try to use the String variable I get an error (See below):
cmd.CommandText = "SELECT UserPswd, StudioID, StudioCode FROM Users WHERE UserName = " & StrUserName
I know there must be something wrong with my syntax ??
Thanks
Jackson

View 5 Replies View Related

SQL Select Statement With A 'string' Variable?

Apr 16, 2008

I'm trying to add a 'change password' control to my site and seem to be having some issues.  I have code that works if I statically define what user is displayed on the form, but I cant get it to detect the 'authenticated' user and show them the reset for for that ID.If I take the "+ myid" out of the select statement and just define the username statically the form works properly.    Error:System.Data.SqlClient.SqlException: The column prefix
'System.Security.Principal' does not match with a table name or alias name used
in the query. Here's a piece of the code that is supposed to detect the current logged in user.  However, it gives the error. (some of the code may be redundant but its not causing issues that I can tell)  public void InitPage()    {            IPrincipal p = HttpContext.Current.User;            String myid = HttpContext.Current.User.ToString();            SqlServer sqlServer = new SqlServer(Util.SqlConnectionString());            DataTable dt;            SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);            SqlDataAdapter cmd1 = new SqlDataAdapter("select * from USER WHERE USER_NAME = "+ myid, cnn);            DataTable UIDtable = new DataTable();            cmd1.Fill(UIDtable);            User_Id.Value = UIDtable.Rows[0]["ID"].ToString();            dt = sqlServer.USER_SELECT(Util.SiteURL(Request.QueryString["Pg"].ToString()), User_Id.Value); 

View 1 Replies View Related

Converting SELECT Output To String

Nov 23, 2005

I'm looking for some good hints and tips for reprogrammin an old VB module I just found.

Basically what it does, is receive an input parameter (an int), does a select [name row] from Names where Name_id = [input parameter] and turns this into a string if multiplenames appear.

E.g. result set: John, Josh, Jock turns it into string "John Josh Jock".

So its piece of cake creating a stored procedure selecting data on the base of an input parameter. Select X from Y where Z = @input... the trick is, I don't know how to do arrays in TSQL as in VB.

In the VB edition I create an array, load the names into it, I do a count on how many row the select returns and then a simple for... next adding the names to the string.

Any good examples on how to do this in a sql-server stored proc?

Thanks,

Trin

P.S. This is what I have pieced together this far:


CREATE PROCEDURE findnames

@number int

AS

DECLARE @instrument varchar(50)
DECLARE @tempinstt varchar(10)

DECLARE medlemcursor CURSOR
FOR
SELECT [MCPS Kode]
FROM DW.dbo.names(NOLOCK)
WHERE number = @number

OPEN medlemcursor

FETCH NEXT FROM medlemcursor INTO @tempinstt
WHILE (@@FETCH_STATUS <> -1)
BEGIN
SET @instrument = @instrument + @tempinstt + '-'
FETCH NEXT FROM medlemcursor INTO @tempinstt
END

CLOSE medlemcursor
DEALLOCATE medlemcursor

SELECT @instrument
GO


Just doesn't seem to work, returns NULL, even though I've checked that the cursor SELECT statement actually returns data,

View 5 Replies View Related

SQL 2012 :: How To Select Last Characters From A String

Jun 19, 2014

I have the following string and am trying to select only the characters before the last "</>". How can I do this?

declare @String varchar(500)
set @String = '<p>Assessed By: Michael Jordan Yagnesh</p>
<p>Reviewed By: Fred Smith</p>
<p>Home Address</p>'

select REVERSE(substring(REVERSE(@String),5,charindex(':',REVERSE(@String))-5))Here is what I tried so far:

[Code] ...

View 4 Replies View Related

SQL Server 2012 :: SELECT A String

Dec 1, 2014

I have string as below:

InvoiceTemplateId= SOURCE.InvoiceTemplateId
,Name= SOURCE.Name
,DetailTotalUnitsQty= SOURCE.DetailTotalUnitsQty
,InsertedDate= SOURCE.InsertedDate
,UpdatedDate= SOURCE.UpdatedDate
,Distributor_Id= SOURCE.Distributor_Id
,InsertedBy= SOURCE.InsertedBy
,UpdatedBy= SOURCE.UpdatedBy

I need a string Like below:

Name= SOURCE.Name
,DetailTotalUnitsQty= SOURCE.DetailTotalUnitsQty
,InsertedDate= SOURCE.InsertedDate
,UpdatedDate= SOURCE.UpdatedDate
,Distributor_Id= SOURCE.Distributor_Id
,InsertedBy= SOURCE.InsertedBy
,UpdatedBy= SOURCE.UpdatedBy

So I need every thing except the First value before first comma .

View 3 Replies View Related

SELECT WHERE IN Comma Delimited String

Jun 3, 2008

Hello

I have a table with column Options where each field contains a comma delimited list of ID numbers.

I want to select any records where a certain ID number appears in that list.

So something like:

SELECT * FROM Table t1
WHERE MyID IN (SELECT Options FROM Table t2 WHERE t1.ID = t2.ID)

But that gives me the error:

Syntax error converting the varchar value '39,20' to a column of data type int.

I feel I'm close though! Could anyone point me in the right direction?

Many thanks

Square

View 3 Replies View Related

Select Statement - Get String Between Brackets

Oct 3, 2014

I'm trying to run a SELECT statement to get two different values from a field that looks like this:

"Sample text [123], Sample text 2 [345]"

The two values I'm trying to grab has to be after the last comma. So in this case, I need to get

Value 1: 345
Value 2: Sample text 2

Is this possible to do? I can't create functions to accomplish this.

View 2 Replies View Related

String Compare In Select Statement

Apr 19, 2007

is there a way to have a select statement which compares a value is like ('%a%','%b%','%c%','%d%','%f%','%l%')

so :

select address
from customers
where address like ('%a%','%b%','%c%','%d%','%f%','%l%')

???

View 6 Replies View Related

How To Select A Datetime With A String Of Date?

Oct 26, 2007



Hello, i try to work a my Pocket PC project. I have a question about SQL.

How to write a sql select dataset from table with a give string date but the column is datetime? I don't know how to convert the date string to datetime.Also the time part in the datetime coulmn have some value in it, how to get over that?

and how to make sure both format is correct? because as i check the msdn, there are many different format in datetime.

For example

using date string XX-XX-XXXX to select dataset in the following table

table with following column
DateTimeStamp
XX-XX-XXXX yy:yy:yy:yyyy



Thank you for helping~

View 1 Replies View Related

SELECT Character In A String (masking)

Aug 15, 2007

Anyone who knows a smarter way to select a special part of a text string.
A have done like this now but mabye the textstring changes. I know that the GO02 in the future will expand.
KnowgoodP_GO02_AA_K_20070807_2010_L.BBB
But the underscore _ sign is like a seperator and will always be there to separate the words.

I need the 20070807_2010 and fomat to 2007-08-07 20:10

SELECT @state = STATE,
@thetime = CONVERT(char(20),STATE_TIME,20),
@id = ID,
@textstrr = TEXTSTRRWHERE SUBSTRING(FILENAME, 21,4)+ '-'+ SUBSTRING(FILENAME, 25,2)+'-'+SUBSTRING(FILENAME, 27,2)+' '+ SUBSTRING(FILENAME, 30,2)+ ':'+ SUBSTRING(FILENAME, 32,2)+':00' between @starttime and @theEndTime

View 8 Replies View Related

Max Of String Column

Nov 8, 2006

I having a column formatted as char(12) being used for indexing. I am not getting the correct max value back from the statement:
"SELECT MAX(ID) FROM STAGING_TABLE"

i.e.
ID column contains 45,999,1726..The returned val for the query above is 999. Any ideas? TIA

View 1 Replies View Related

How To Get Csv String From Column

Dec 14, 2007

Hi All,
I have a table which contains values like this :

Column 1 Column 2

A 1
A 2

A 3
B 1

B 2



In need the output in this format:
Col1 Col 2
A 1,2,3
B 1,2


Can anyone help me with this ????

View 3 Replies View Related

How To Select Column Without Selecting A Column Name

Feb 17, 2004

I want to know how to select a Column without selecting a column name

View 6 Replies View Related

2 Sql Select Statements In 1 Sql String Just Wont Work!

Jul 5, 2007

hi there, i have a bit of a strange problem, and i must be doing something wrong because this works with insert and update statements in other pages. What is going on is that i am trying to do 2 select statements in the same bit of code so i dont have to open a datareader twice, but if i put the delivery charge select before the other it seems to get it, but if i put it after it does not, i just cant work it out! i have posted my code below for you all to have a look at because im stumped!
//gets order id and customer id and puts them to strings and int to be used laterstring strCustID = Request.QueryString["qsnOrderCustID"].ToString();
int intCustID = Convert.ToInt32(strCustID);string strOrderID = Request.QueryString["orderID"].ToString();int intOrderID = Convert.ToInt32(strOrderID);
 
//This is the sql statement.string sql = "SELECT [sub_total], [VAT], [Total] FROM tbl_order WHERE order_ID = " + intOrderID + ";" + "SELECT [del_cost] FROM tbl_del WHERE order_ID = " + intOrderID;
 
//This creates a sql command which executes the sql statement.SqlCommand sqlCmd = new SqlCommand(sql, myConn);
myConn.Open();SqlDataReader dr = sqlCmd.ExecuteReader();
 
//This reads the first result from the sqlReader
dr.Read();
//This sets the title label text to the value of the description column.
try
{
 
//fill these labels with the first select statement lblSubTot.Text = dr["sub_total"].ToString();
lblVAT.Text = dr["VAT"].ToString();lblOrderTotal.Text = dr["Total"].ToString();lblDelCharge.Text = dr["del_cost"].ToString();
 
//fill this label with the second select statementlblDelCharge.Text = dr["del_cost"].ToString();
}catch (Exception except)
{string strError = Convert.ToString(except);
}
finally
{
myConn.Close();
}
any ideas would be great! thanks
Jez

View 2 Replies View Related

SQL Select Command.. Allow X Amount Of Characters From A String

Jan 17, 2008

Ok so we gotSELECT this, that, others FROM some.database WHERE this=@this So in the database the others field is a string that can have up to 200 characters, but on this particular data pull I only want to pull the first 50 characters of the others field.  How can I do that?  Thanks.     

View 4 Replies View Related

SELECT Items Based On String Manipulation

Oct 25, 2005

I am having some trouble creating a query that will preform some string manipulations on a field, and include this as part of the WHERE clause

For example I want to do something like this:


Code:

SELECTTable1.Column1,
Table1.Column2,
Table1.Column3,
Table2.Column1

FROMTable1
INNER JOIN Table2 ON Table1.UID = Table2.UID

WHERE(SET @Temp = Table2.Column1

--remove all 0's
SET @k = patindex('%[^0 ]%', @Temp)
WHILE @k> 0
BEGIN
SET @Temp = replace(@Temp, substring(@Temp, @k, 1), '')
SET @k= patindex('%[^0 ]%', @Temp)
END
SELECT @Temp
) = ''



But of course this isn't working so much. I am wondering if I have to use a cursor?

View 1 Replies View Related

Append String To Field Value In Select List

Jul 26, 2004

How can I append a string to the field value in the select list


SELECT Code + '-20' FROM tb.....

I want to the above to return 2000-20 for example.

How can I do this?

Mike B

View 1 Replies View Related







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