If STATEMENT Within Select Statement Syntax
Hi,
I am a newbie to this site and hope someone can help....
I have a select statement which I would like to create an extra column and put an if statement in it.... Current syntax is:
if(TL_flag= '1', "yes") as [Trial Leave]
it is coming up with an error.... I can use Select case but I should not need to as this should work?
Any ideas?
View Complete Forum Thread with Replies
Related Forum Messages:
LIKE Syntax In A SELECT Statement
What is the syntax for making a query using like, the below is my code <asp:SqlDataSource ID="Search" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" ProviderName="<%$ ConnectionStrings:DatabaseConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [Products]WHERE category LIKE %@category%"> <SelectParameters> <asp:QueryStringParameter Name="category" QueryStringField="category" Type="string" /> </SelectParameters> </asp:SqlDataSource> Its giving a syntax error but I dont know how to change it. Please advise, thanks!
View Replies !
SQL Syntax With For Select Like Statement
Hello, I have the following statement that I am trying to convert to a "like" statement in a SqlDataSource for a web application. I can't seem to get the syntax correct. Would someone be able to assist with this? Thanks! SELECT * FROM [Employees] WHERE ([LName] = @LName) ORDER BY [LName], [FName] Something like below. SELECT * FROM [Employees] WHERE ([LName] LIKE '@LName%') ORDER BY [LName], [FName]
View Replies !
Syntax For IF-THEN In SQL Select Statement
I need to use IF-THEN in a SQL Select statement. Using Google I have found a couple of obscure references to this but nothing that I can use. Tried various combinations without luck. Can anyone point me to a good resource or supply a simple example of proper syntax? Thanks in advance for any help provided.
View Replies !
In Code Behind, What Is Proper Select Statement Syntax To Retrieve The @BName Field From A Table?
In Code Behind, What is proper select statement syntax to retrieve the @BName field from a table?Using Visual Studio 2003SQL Server DB I created the following parameter:Dim strName As String Dim parameterBName As SqlParameter = New SqlParameter("@BName", SqlDbType.VarChar, 50) parameterBName.Value = strName myCommand.Parameters.Add(parameterBName) I tried the following but get error:Dim strSql As String = "select @BName from Borrower where BName= DOROTHY V FOWLER " error is:Line 1: Incorrect syntax near 'V'. 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: Line 1: Incorrect syntax near 'V'. Source Error: Line 59: Line 60: Line 61: myCommand.ExecuteNonQuery() 'Execute the query
View Replies !
Select Statement Within Select Statement Makes My Query Slow....
Hello... im having a problem with my query optimization.... I have a query that looks like this: SELECT * FROM table1 WHERE location_id IN (SELECT location_id from location_table WHERE account_id = 998) it produces my desired data but it takes 3 minutes to run the query... is there any way to make this faster?... thank you so much...
View Replies !
Multiple Tables Used In Select Statement Makes My Update Statement Not Work?
I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly. My problem is that the table I am pulling data from is mainly foreign keys. So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys. I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit. I run the "test query" and everything I need shows up as I want it. I then go back to the gridview and change the fields which are foreign keys to templates. When I edit the templates I bind the field that contains the string value of the given foreign key to the template. This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value. So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors. I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode. I make my changes and then select "update." When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing. The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work. When I remove all of my JOIN's and go back to foreign keys and one table the update works again. Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People]. My WHERE is based on a control that I use to select a person from a drop down list. If I run the test query for the update while setting up my data source the query will update the record in the database. It is when I try to make the update from the gridview that the data is not changed. If anything is not clear please let me know and I will clarify as much as I can. This is my first project using ASP and working with databases so I am completely learning as I go. I took some database courses in college but I have never interacted with them with a web based front end. Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian
View Replies !
Using Conditional Statement In Stored Prcodure To Build Select Statement
hiI need to write a stored procedure that takes input parameters,andaccording to these parameters the retrieved fields in a selectstatement are chosen.what i need to know is how to make the fields of the select statementconditional,taking in consideration that it is more than one fieldaddedfor exampleSQLStmt="select"if param1 thenSQLStmt=SQLStmt+ field1end ifif param2 thenSQLStmt=SQLStmt+ field2end if
View Replies !
TSQL - Use ORDER BY Statement Without Insertin The Field Name Into The SELECT Statement
Hi guys, I have the query below (running okay): Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' FROM myTables WHERE Conditions are true ORDER BY Field01 The results are just as I need: Field01 Field02 ------------- ---------------------- 192473 8461760 192474 22810 Because other reasons. I need to modify that query to: Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' INTO AuxiliaryTable FROM myTables WHERE Conditions are true ORDER BY Field01 SELECT DISTINCT [Field02] FROM AuxTable The the results are: Field02 ---------------------- 22810 8461760 And what I need is (without showing any other field): Field02 ---------------------- 8461760 22810 Is there any good suggestion? Thanks in advance for any help, Aldo.
View Replies !
How To Write Select Statement Inside CASE Statement ?
Hello friends, I want to use select statement in a CASE inside procedure. can I do it? of yes then how can i do it ? following part of the procedure clears my requirement. SELECT E.EmployeeID, CASE E.EmployeeType WHEN 1 THEN select * from Tbl1 WHEN 2 THEN select * from Tbl2 WHEN 3 THEN select * from Tbl3 END FROM EMPLOYEE E can any one help me in this? please give me a sample query. Thanks and Regards, Kiran Suthar
View Replies !
Help With Delete Statement/converting This Select Statement.
I have 3 tables, with this relation: tblChats.WebsiteID = tblWebsite.ID tblWebsite.AccountID = tblAccount.ID I need to delete rows within tblChats where tblChats.StartTime - GETDATE() < 180 and where they are apart of @AccountID. I have this select statement that works fine, but I am having trouble converting it to a delete statement: SELECT * FROM tblChats c LEFT JOIN tblWebsites sites ON sites.ID = c.WebsiteID LEFT JOIN tblAccounts accounts on accounts.ID = sites.AccountID WHERE accounts.ID = 16 AND GETDATE() - c.StartTime > 180
View Replies !
Using Select Statement Result In If Statement Please Help
Hello How can i say this I would like my if statement to say: if what the client types in Form1.Cust is = to the Select Statement which should be running off form1.Cust then show the Cust otherwise INVALID CUSTOMER NUMBER .here is my if statement. <% If Request.Form("Form1.Cust") = Request.QueryString("RsCustNo") Then%> <%=Request.Params("Cust") %> <% Else %> <p>INVALID CUSTOMER NUMBER</p> <% End If%> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RsCustNo %>" ProviderName="<%$ ConnectionStrings:RsCustNo.ProviderName %>" SelectCommand="SELECT [CU_CUST_NUM] FROM [CUSTOMER] WHERE ([CU_CUST_NUM] = ?)"> <SelectParameters> <asp:FormParameter FormField="Cust" Name="CU_CUST_NUM" Type="String" /> </SelectParameters> </asp:SqlDataSource>any help would be appreciated
View Replies !
Sql Syntax Statement
Here is an sql query but it keeps giving me an error of (Incorrect syntax near keywork ON) here is the sql, don't get why this doe not work when I have done it this way multiple times. select DISTINCT c.strSSN, p.sidstrNAME_IND, p.sidstrGR_ABBR_CODE, p.sidstrSSN_SM, p.sidstrST_ADDR, p.sidstrADDR_CITY, p.sidstrSTATES_US, p.sidstrZIP_CODE, p.sidstrPAY_GR, p.sidstrMARTL_STAT, p.sidstrNBR_EXEMPT, p.sidstrST_TAX_CODE, u.lsdbstrPHONE_NBR_HOME, case when sidstrTech_SVC_Code in ('M', 'R', 'S', 'T', 'U', 'Z') then case when sidstrACT_STAT_PROG in ('5', 'A', 'E', 'F', 'N', 'R', 'S', 'T') then 'AGR' else 'Tech' end else 'M-Day' end as status from tblAssignedPersonnel as c on ap.strssn = p.sidstrSSN_SM Inner Join cms.dbo.tblLSDB as u on u.lsdbstrSSN_SM = c.strSSN inner joincms.dbo.tblSidpers as p on ap.strSSN = p.sidstrSSN_SM where intUICID = (select intUICID from tblUIC where strUIC = '2' and intTaskForceID = '1') order by p.sidstrNAME_IND
View Replies !
What's The Right Syntax Of This Sql Statement?
Hi, I created a sqldatasource (sql server) and a gridview.In the aspx file, i can see the selectcommand: SelectCommand="select email from mytable" Now, i want to modify something in the selectcommand produced in the aspx file, in order to get the emails in clickable mode. I knwow i have to add a string like: <a hef="mailto:mailaddress">mailadress</a> So i tried this: SelectCommand="select '<a href="mailto:'+ email +'">' , email + '</a>' from email But this gives the error: "tag is not well formed".The problem is the " around mailto: Thanks Cl.
View Replies !
Using IF...Else Statement SELECT Statement
Hi All, Can some one point me in the right direction in how to construct my SQL query within my cursor? I Have got a cursor which i am using to iterate through a table, What i am trying to do is in my statement(used to open the cursor) is compare 2 tables (the one which my cursor is iterating) to see if there is a matching row in the other table (using both tables ID's Like So: SELECT column_List FROM Table1 WHERE Table1_id = Table2_id so for each row my cursor checks if there is a corresponding match in table2... but i would like to write to an error log and do other statements if there is no match how do i add this condition to my statement either using an if...else statement proceeding to the next row? here is the statment i attempted to write: SELECT column_List FROM table1 WHERE Table1_id = Table2.id now i want to incoporate the statements below into the statement above as a condition when table1.id <> table2.id IF table1.id <> table2.id BEGIN SET @DebugMessage = 'data not live.' RAISERROR (@DebugMessage, 16, 1) WITH LOG END essentially what i am trying to sayin my statement is: go to the first row check if it has a match in table 2, if there is no match execute a number of statements such as error loging e.t.c go to the next row repeat the previous statements ...i also looked through some Case...When statements am just not sure how to put in the condition thanks in advance
View Replies !
SQL Statement Syntax Error?
SELECT DISTINCT CONVERT (nvarchar , tblSubject.Subject, 108) AS SubjectTime, CONVERT (nvarchar(11), tblSubject.Subject, 100) AS Date FROM tblLooker,tblSubject,tblStop WHERE NOT (SELECT DISTINCT CONVERT (nvarchar , tblSubject.Subject, 108) AS SubjectTime, CONVERT (nvarchar(11), tblSubject.Subject, 100) AS Date FROM tblSubject, tblLooker, tblStop WHERE tblSubject.Subject > tblLooker.Looker AND tblSubject.Subject < tblStop.Stop AND tblLooker.id = tblStop.id) Msg 170, Level 15, State 1, Line 5Line 5: Incorrect syntax near ')'. Can anyone tell me why this is not working? Thanks
View Replies !
Incorrect Syntax Near ','. Sql Statement
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString()); SqlCommand myCommand = new SqlCommand("SELECT (Deadline, Description, Headline, AddressField, OrganizationField, NameField, FileField, EmailField, CommentField) FROM RegistrationFormDB_Info WHERE (UserName = @UserName AND TournamentName = @TournamentName)", myConnection); SqlParameter myParam = new SqlParameter(); myParam.ParameterName = "@UserName"; myParam.Value = User.Identity.Name; myCommand.Parameters.Add(myParam); myParam = new SqlParameter(); myParam.ParameterName = "@TournamentName"; myParam.Value = Request.QueryString["TournamentName"]; myCommand.Parameters.Add(myParam); myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); <====================== I continue to get this error and I can't figure out the problem! Anything helps. Thank you very much.
View Replies !
Incorrect Syntax Using IF Statement
Hi,I'm new to SQL Server Programming, I work with ASP a lot, but latelyI've been trying to create Stored Procedures, etc. I'm having aproblem writing a simple IF statement.. I don't seem to understand whyit's giving me this error. I've search around on Google Groups, but Istill don't get it.=================USE msdbIF NOT EXISTS (SELECT * FROM sysjobs WHERE name = 'Scheduled Nightfax')END=================My error is:Server: Msg 156, Level 15, State 1, Line 5Incorrect syntax near the keyword 'END'.Thanks for any help.
View Replies !
Can I Reduce This Sql Statement Syntax?
this is SQL statement in Stored procedure to calculate the last date of a month : (can it reduce to fewer lines??? help!!!!!) argument pass in : @empmt_dt datetime argument return : @last_dt datetime declare @empmt_dt datetime, @mth tinyint, @yr smallint select @empmt_dt = "12/9/2000" select @yr = datepart(year, @empmt_dt) select @mth = datepart(month, @empmt_dt) IF @mth = 12 BEGIN SELECT @mth = 1 SELECT @yr = @yr + 1 END ELSE BEGIN SELECT @mth = @mth + 1 END SELECT dateadd(dd, -1, convert(datetime, STR(@mth,2,0) + '/01/' + STR(@yr,4,0)))
View Replies !
CASE Statement Syntax
Can someone tell me what is wrong with my syntax? I am getting several errors: Incorrect syntax near keyword 'CASE' Incorrect syntax near keyword 'WHEN' Incorrect syntax near '@Tablename' CREATE PROCEDURE al_readcampsignup @User_ID int, @Pagenumber smallint, @Tablename varchar(10) AS CASE @Mypagenumber WHEN 1 THEN SELECT Blah FROM tempcampsignup WHERE Camp_ID = @User_ID WHEN 2 THEN SELECT Blah FROM @Tablename WHERE Camp_ID = @User_ID WHEN 3 THEN SELECT Blah FROM @Tablename WHERE Camp_ID = @User_ID END Thanks
View Replies !
EFFECTIVE SQL STATEMENT SYNTAX
Hi all, I am a java developer having little bit knowledge in sql statements. can any body guide me what is the effective way of using sql statement to achieve the following goal. here is the requirement. 1. There are 2 tables A & B. 2.The table 'B' may or maynot have an equivalent entry for the primary key of table a. 3. select column1 (of A), column 2(of B) from table a and b. 4. now column2 should give a value, if there is a corresponding entry in table b.other wise null. 5. at any time there may be 0 to 1 record in table b for the primary of table a. thanks in advance krishna
View Replies !
If Statement ... Syntax Error
hi, i've got this code Code Snippet go create proc dbo.sp_GetFilterOrgIDs(@ID int) as select distinct O.ID from Organisations O if (@ID != 0) begin where O.ID = @ID end and am getting Incorrect syntax near the keyword 'where'. any idea why??
View Replies !
IIF Statement Has Syntax Error...please Help...
I am trying to figure out the syntax for the following: =iif(fields!ExtTripCount.value = 1,sum(Fields!ExtTripCount.value),0) / (count(fields!SvcCallNumber.value))* 100 I am trying to take all the trips that equal a one and divide them by the total number of service calls and then multiple them by 100 to get the percentage. I am receiving the following errror: "The value expression refers to the field 'SvcCallNumber'. Report item expressions can only refer to fields within the current dta set scope or, if inside an aggregate, the specified data set scope...
View Replies !
SYNTAX Help, Correct Way To Use LIKE In Statement
Hi, I'm new to SQL and was wondering if there was an easier way to filter data. I have two tables - The first table called Names of Companies has a column named: NAMES NAMES XYZ Company ABC Limited Liability Company ZZZ Corporation KKK Inc. ABC Inc. The second table called Keywords has a column named: WORDS WORDS Company Limited I want to search for all NAMES that contain the WORDS in some form The results should be: NAMES XYZ Company ABC Limited Liability Company Technically, I can get the results I want by manually typing into the SQL statement all the words that appear in the WORDS column. SELECT * FROM [Names of Companies] WHERE [Names of Companies].Names Like "*Company*" Or ([Names of Companies].Names) Like "*limited*")); But is there a way that I reference the table Keyword instead of typing into the query statement all the words that appear in the column WORD? I have a lot of words to search for. Can anyone recommend a better way to do this? Thanks for all your help!
View Replies !
Syntax Error In UPDATE Statement.
Hi forum, im converting some code and have an issue with th following code!!! many thanks for good advice, Paul Line 55: SQLa = "UPDATE counted SET " & y & " = " & intClick & ", total = " & intTotal & " WHERE ID = " & RSpc.Fields("pc").ValueLine 56: Conn.Execute(SQLa) System.Runtime.InteropServices.COMException: Syntax error in UPDATE statement. Dim SQLa As String
View Replies !
Syntax Error On Insert Statement
Ok, the following four lines are four lines of code that I'm running, I'll post the code and then explain my issue: sqlCommand = New SQLCommand("INSERT INTO Bulk (Bulk_Run, Bulk_Totes, Bulk_Drums, Bulk_Boxes, Bulk_Bags, Bulk_Bins, Bulk_Crates) VALUES (" & RunList(x,0) & ", " & Totes & ", " & Drums & ", " & Boxes & ", " & Bags & ", " & Bins & ", " & Crates & ")", Connection) sqlCommand.ExecuteNonQuery() sqlCommand = New SQLCommand("INSERT INTO Presort (Presort_Run, Presort_Totes, Presort_Drums, Presort_Boxes, Presort_Bags, Presort_Bins, Presort_Crates) VALUES (" & RunList(x,0) & ", " & Totes & ", " & Drums & ", " & Boxes & ", " & Bags & ", " & Bins & ", " & Crates & ")", Connection) sqlCommand.ExecuteNonQuery() The two tables (Bulk & Presort) are <b>exactly</b> the same. This includes columns, primary keys, IDs, and even permissions. If I run the last two liens (the INSERT INTO Presort) then it works fine without error. But whenever I run the first two lines (the INSERT INTO Bulk) I get the following error: Incorrect syntax near the keyword 'Bulk'. Anyone have any ideas, thanks
View Replies !
Syntax Error On INSERT Statement
Here is my insert statement: StringBuilder sb = new StringBuilder(); sb.Append("INSERT INTO patients_import_test "); sb.Append("(Referral_Number,Referral_Date,FullName,Patient_ien,DOB,FMP,SSN_LastFour,Race_Id,PCM,Age) "); sb.Append("VALUES(@rnum,@rdate,@fname,@patid,@birthDate,@fmp,@ssan,@race,@pcm,@age) "); sb.Append("WHERE Referral_Number NOT IN ( SELECT Referral_Number FROM patients_import_test )");I'm getting an "Incorrect syntax near the keyword 'WHERE'".If I remove the WHERE clause the INSERT statement work fine.
View Replies !
Syntax Error In UPDATE Statement.
I have place a lblmessage.text = ex.Message to trace what happen and it show me a syntax error in update happen. I don't know whats wrong with my syntax. Can someone help me on this? <%@ Page Language = "vb" Debug="true" %> <%@ import namespace= "system.data" %> <%@ import namespace= "system.data.oledb" %> <script runat="server"> 'set up connection dim conn as new oledbconnection _ ("provider = microsoft.jet.oledb.4.0;" & _ "data source = c:aspnetdataanking.mdb") sub page_load(sender as object, e as eventargs) if not page.ispostback then filldatagrid() end if end sub sub submit (sender as object, e as eventargs) 'insert new data dim i,j as integer dim params(7) as string dim strtext as string dim blngo as boolean = true j = 0 for i = 0 to addpanel.controls.count -1 if addpanel.controls(i).gettype is _ gettype (textbox) then strtext = ctype(addpanel.controls(i), _ textbox).text if strtext <> "" then params(j) = strtext else blngo = false lblmessage.text = lblmessage.text & _ "you forgot to enter a value for " & _ addpanel.controls (i).id & "<p>" lblmessage.style ("forecolor")= "red" end if j=j+1 end if next if not blngo then exit sub end if dim strsql as string = "INSERT INTO tblusers " & _ "(firstname, lastname, address, city, state, " & _ "zip, phone) values (" & _ "'" & params(0) & "'," & _ "'" & params(1) & "'," & _ "'" & params(2) & "'," & _ "'" & params(3) & "'," & _ "'" & params(4) & "'," & _ "'" & params(5) & "'," & _ "'" & params(6) & "')" executestatement(strsql) filldatagrid() end sub sub dgdata_edit (sender as object, e as datagridcommandeventargs) filldatagrid(e.item.itemindex) end sub sub dgdata_delete (sender as object, e as datagridcommandeventargs) dim strsql as string = "DELETE FROM tblusers " & _ "WHERE userid = " & e.item.itemindex + 1 executestatement(strsql) filldatagrid() end sub sub dgdata_update (sender as object, e as datagridcommandeventargs) if updatedatastore(e) then filldatagrid(-1) end if end sub sub dgdata_cancel (sender as object, e as datagridcommandeventargs) filldatagrid(-1) end sub sub dgdata_pageindexchanged (sender as object, e as datagridpagechangedeventargs) dgdata.databind() end sub function updatedatastore (e as datagridcommandeventargs) as boolean dim i,j as integer dim params(7) as string dim strtext as string dim blngo as boolean = true j = 0 for i =1 to e.item.cells.count - 3 strtext = ctype(e.item.cells(i).controls(0), _ textbox).text if strtext <> "" then params(j) = strtext blngo = true j= j+1 else blngo = false lblmessage.text = lblmessage.text & _ "you forgot to enter a value<p>" end if next if not blngo then return false exit function end if dim strsql as string = "update tblusers SET " & _ "Firstname.value = '" & params(0) & "'," & _ "lastname.value = '" & params(1) & "'," & _ "address.value = '" & params(2) & "'," & _ "city.value = '" & params(3) & "'," & _ "state.value = '" & params(4) & "'," & _ "zip.value = '" & params(5) & "'," & _ "phone.value = '" & params(6) & "'," & _ " WHERE Userid = " & ctype(e.item.cells(0). _ controls(1), label).text executestatement (strsql) return blngo end function sub filldatagrid (optional editindex as integer = -1) ' open connection dim objcmd as new oledbcommand _ ("select * from tblusers", conn) dim objreader as oledbdatareader try objcmd.connection.open () objreader = objcmd.executereader() catch ex as exception lblmessage.text = "error retrieving from the " & _ "database." end try dgdata.datasource = objreader if not editindex.equals(nothing) then dgdata.edititemindex = editindex end if dgdata.databind() objreader.close objcmd.connection.close() end sub function executestatement (strsql) dim objcmd as new oledbcommand(strsql, conn) try objcmd.connection.open() objcmd.executenonquery() catch ex as exception lblmessage.text = ex.message end try objcmd.connection.close() end function </script> <html><body> <asp:label id= "lblmessage" runat ="server" /> <form runat= "server"> <asp:datagrid id = "dgdata" runat ="server" bordercolor = "black" gridlines="vertical" cellpadding ="4" cellspacing="0" width = "100%" autogeneratecolumns = "False" ondeletecommand = "dgdata_delete" oneditcommand = "dgdata_edit" oncancelcommand = "dgdata_cancel" onupdatecommand = "dgdata_update" onpageindexchanged= "dgdata_pageindexchanged" font-names = "arial" font-size="8pt" showfooter = "true" headerstyle-backcolor= "#cccc99" footerstyle-backcolor= "#cccc99" itemstyle-backcolor= "#ffffff" alternatingitemstyle-backcolor="#cccccc"> <columns> <asp:templatecolumn headertext="id"> <itemtemplate> <asp:label id = "name" runat = "server" text = '<%# container.dataitem("userid")%>' /> </itemtemplate> </asp:templatecolumn> <asp:boundcolumn headertext = "firstname" datafield = "firstname" /> <asp:boundcolumn headertext = "lastname" datafield = "lastname" /> <asp:boundcolumn headertext = "address" datafield = "address" /> <asp:boundcolumn headertext = "city" datafield = "city" /> <asp:boundcolumn headertext = "state" datafield = "state" /> <asp:boundcolumn headertext ="zip" datafield = "zip" /> <asp:boundcolumn headertext ="phone" datafield = "phone" /> <asp:editcommandcolumn edittext="Edit" canceltext="cancel" updatetext="update" headertext = "edit"/> <asp:buttoncolumn headertext = "delete?" text = "X" commandname = "delete" buttontype = "pushbutton" /> </columns> </asp:datagrid><p> <asp:panel id= "addpanel" runat = "server"> <table> <tr> <td width ="100" valign = "top"> first and last name: </td> <td width ="300" valign = "top"> <asp:textbox id= "tbfname" runat = "server"/> <asp:textbox id= "tblname" runat = "server"/> </td> </tr> <tr> <td valign = "top">address:</td> <td valign= "top"> <asp:textbox id= "tbaddress" runat = "server"/> </td> </tr> <tr> <td valign = "top">city, state, zip:</td> <td valign= "top"> <asp:textbox id= "tbcity" runat = "server"/> <asp:textbox id= "tbstate" runat = "server"/> <asp:textbox id= "tbzip" runat = "server" size=5 /> </td> </tr> <tr> <td valign= "top">phone:</td> <td valign= "top"> <asp:textbox id= "tbphone" runat = "server" size = 11/><p> </td> </tr> <tr> <td colspan = "2" valign = "top" allign = "right"> <asp:button id = "btsubmit" runat ="server" text ="add" onclick = "submit" /> </td> </tr> </table> </asp:panel> </form> </body></html>
View Replies !
Continuation Of Long SQL Statement Syntax
Hi All -I am updating four values. What is the proper syntax to have thefollowing 4 update statements as one statement?set objRec = objDB.Execute("Update orientform set session = '" &strSession & "' where id = '" & strid & "'")set objRec = objDB.Execute("Update orientform set fname = '" & strfname& "' where id = '" & strid & "'")set objRec = objDB.Execute("Update orientform set gender = '" &strgender & "' where id = '" & strid & "'")set objRec = objDB.Execute("Update orientform set lname = '" & strlname& "' where id = '" & strid & "'")Thanks,Joey
View Replies !
Syntax Error In INSERT INTO Statement.
Public DBString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Q:VoicenetRTS FolderRTS ChargesAccountscosting.mdb" Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click Dim connstring As New OleDbConnection(DBString) connstring.Open() Dim searchstring As String = "SELECT * FROM Costings1" Dim da As New OleDbDataAdapter(searchstring, connstring) Dim DS As New DataSet() Dim dt As DataTable = DS.Tables("Costings1") da.FillSchema(DS, SchemaType.Source, "Costings1") da.Fill(DS, "Costings1") Dim cb As New OleDbCommandBuilder(da) da.InsertCommand = cb.GetInsertCommand da.UpdateCommand = cb.GetUpdateCommand Dim dr As DataRow = DS.Tables("Costings1").NewRow dr("Key") = TextBox1.Text dr("CODE") = TextBox2.Text dr("Element") = TextBox3.Text etc... DS.Tables("Costings1").Rows.Add(dr) da.Update(DS, "Costings1") <<<<<<<<<<<Syntax error in INSERT INTO statement. There are no spaces in the field names.
View Replies !
Insert Into Statement Syntax Error
Hi, I have a problem as shown below Server Error in '/ys(Do Not Remove!!!)' Application. Syntax error in INSERT INTO statement. 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.OleDb.OleDbException: Syntax error in INSERT INTO statement. Source Error: Line 8: <Script runat="server"> Line 9: Private Sub InsertAuthorized(ByVal Source As Object, ByVal e As EventArgs) Line 10: SqlDataSource1.Insert() Line 11: End Sub ' InsertAuthorized Line 12: </Script> Source File: C:Documents and SettingsDream_AchieverDesktopys(Do Not Remove!!!)Authorizing.aspx Line: 10 Stack Trace: [OleDbException (0x80040e14): Syntax error in INSERT INTO statement.] System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +177 System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +194 System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +56 System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +105 System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +88 System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +392 System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +410 System.Web.UI.WebControls.SqlDataSource.Insert() +13 ASP.authorizing_aspx.InsertAuthorized(Object Source, EventArgs e) in C:Documents and SettingsDream_AchieverDesktopys(Do Not Remove!!!)Authorizing.aspx:10 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919 And part of my program is as shown <Script runat="server"> Private Sub InsertAuthorized(ByVal Source As Object, ByVal e As EventArgs) SqlDataSource1.Insert() End Sub ' InsertAuthorized </Script> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DIP1ConnectionString %>" ProviderName="<%$ ConnectionStrings:DIP1ConnectionString.ProviderName %>" InsertCommand="Insert Into Authorize (Army ID,Tag No,Vehicle ID,Vehicle Type,Prescribed Route,Start Time, End Time) VALUES (@ArmyID, @TagNo, @VehicleID, @VehicleType, @PrescribedRoute, @StartTime, @EndTime)"> <insertparameters> <asp:formparameter name="ArmyID" formfield="ArmyID" /> <asp:formparameter name="TagNo" formfield="TagNo" /> <asp:formparameter name="VehicleID" formfield="VehicleID" /> <asp:formparameter name="VehicleType" formfield="VehicleType" /> <asp:formparameter name="PrescribedRoute" formfield="PrescribedRoute" /> <asp:formparameter name="StartTime" formfield="StartTime" /> <asp:formparameter name="EndTime" formfield="EndTime" /> </insertparameters> </asp:SqlDataSource> Anybody can help? thanks
View Replies !
CASE Statement Syntax Problem
I am attempting to mask a user's SS# based on Users.DisplaySSN. I have gone over the code time and time again and can't find where the error is. Error I'm getting: Incorrect syntax near the keyword 'AS'. Here's where the error lies: CASE (SELECT DisplaySSN FROM Users WHERE Users.UserID = @UserID) WHEN False THEN 'xxx-xx-xxxx' + right(SocialSecurityNumber,0) AS SocialSecurityNumber ELSE vwEmp.SocialSecurityNumber END
View Replies !
Can You Please Correct My Syntax For If Statement In Stored Proc
I am using @strsql to construct the where condition for a select query. Can you please correct my syntax. DECLARE @strsql nvarchar(2000) IF @ProgNO <> '' then strsql = WHERE ProgNO = @ProgNO end if If @ProjNO <> '' then if strsql <> '' then strsql = strsql & " and ProjNO =@ProjNO ELSE strsql = wHERE ProjNO =@ProjNO END IF END IF Thank you very much.
View Replies !
Syntax Error With "alter Table" Statement
Folks! What is wrong with my syntax with the following command?: alter table EmployeeInfo alter column OriginDate smalldatetime not null default getdate() I'm getting: Incorrect syntax near the keyword 'default' Currently, in my table OriginDate is nullable with no default. Thanks in advance for your help! APF
View Replies !
Syntax Check Needed On Case Statement
Hello experts! I have a case statement that provides filtering of hours during certain days of the week. An example is the data I want to show on Sunday is different from the rest of the week. I am using.... Code Snippet WHERE ((CASE WHEN Datepart(dw, TestDateTime) = 1 AND datepart(hh, TestDateTime) BETWEEN 8 AND 22 THEN 1 WHEN Datepart(dw, TestDateTime) >= 2 AND datepart(hh, TestDateTime) BETWEEN 6 AND 23 OR datepart(hh, TestDateTime) BETWEEN 0 AND 2 THEN 1 ELSE 0 END) >= @ShowCore) Esentially it gives a parameter (@showcore) to where it shows the filtered hours when 1 is selected, and all hours if 0 is selected. Basically, Sunday I want to show transaction from between 8am and 10pm, All other days would be 12am - 2am and 6am to 11:59:59 when selecting 1 as the parameter. Any help is appreciated.
View Replies !
UPDATE Statement Syntax Help Required C# && SqlDataSource Control
Hi, I need to UPDATE the IP Address of a newly created user into a table (the value is currently set to default - " Not Available"), and I really dont know the syntax required to do this. So far I've derived all the variables needed using the following code: protected void ContinueButton_Click(object sender, EventArgs e) { //Get the ip address and put it into the customer table - (the instance of this user now exists) MembershipUser _membershipUser = Membership.GetUser(); Guid UserId = (Guid)_membershipUser.ProviderUserKey;<--------------------------------------------------------------I can see the UserId here if I pause the prog SqlDataSource customerDataSource = new SqlDataSource(); customerDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); customerDataSource.UpdateParameters.Add("IPAddress", Request.UserHostAddress.ToString());<---------------------------------------I can see the IPAddress here customerDataSource.UpdateCommandType = SqlDataSourceCommandType.Text; what next I've not got a clue as to what to write next. There is a try / catch statement after this using : rowsAffected = customerDataSource.Update(); which remains at 0 no matter what I try. Any help greatly appreciated.
View Replies !
Incorrect Syntax Near The Keyword 'EXEC' (Dynamic Sql Statement Error)
Following is the stored procedure iam trying to create.Here i am trying to First create a table with the table name passed as parameter Second I am executing a dynamic sql statement ("SELECT @sql= 'Select * from table") that returns some rows. Third I want to save the rows returned by the dynamic sql statement ("SELECT @sql= 'Select * from table") in the tablei created above.All the columns and datatypes are matching. This table would be further used with cursor. Now i am getting a syntax error on the last line.Though i doubt whether the last 3 lines will execute properly.Infact how to execute a sp_executesql procedure in another dynamic sql statement.ANy suggestions will be appreciated. CREATE PROCEDURE [dbo].[sp_try] @TempTable varchar(25) AS DECLARE @SQL nvarchar(MAX) DECLARE @SQLINSERT nvarchar(MAX) BEGIN --create temp table SELECT @Sql= N'CREATE TABLE ' + QUOTENAME(@TempTable) + '( ContactName varchar (40) NOT NULL , ContactId varchar (30) NOT NULL , ContactrMessage varchar (100) NOT NULL, )' EXEC sp_executesql @Sql, N'@TempTable varchar(25)', @TempTable = @TempTable SELECT @sql= 'Select * from table' SELECT @sqlinsert = 'INSERT INTO ' + quotename( @TempTable ) SELECT @sqlinsert = @sqlinsert + EXEC sp_executesql @sql, N'@Condition varchar(max)', @Condition=@Condition EXEC sp_executesql @SQLINSERT, N'@TempTable varchar(25)', @TempTable = @TempTable
View Replies !
System.Data.OleDb.OleDbException: Syntax Error In INSERT INTO Statement.
Hi All I'm having a bit of trouble with an sql statement being inserted into a database - here is the statement: string sql1; sql1 = "INSERT into Customer (Title, FirstName, FamilyName, Number, Road, Town,"; sql1 += " Postcode, Phone, DateOfBirth, email, PaymentAcctNo)"; sql1 += " VALUES ("; sql1 += "'" + TxtTitle.Text + "'," ; sql1 += "'" + TxtForename.Text + "'," ; sql1 += "'" + TxtSurname.Text + "'," ; sql1 += "'" + TxtHouseNo.Text + "',"; sql1 += "'" + TxtRoad.Text + "',"; sql1 += "'" + TxtTown.Text + "',"; sql1 += "'" + TxtPostcode.Text + "',"; sql1 += "'" + TxtPhone.Text + "',"; sql1 += "'" + TxtDob.Text + "',"; sql1 += "'" + TxtEmail.Text + "',"; sql1 += "'" + TxtPayAcc.Text + "')"; Which generates a statement like:INSERT into Customer (Title, FirstName, FamilyName, Number, Road, Town, Postcode, Phone, DateOfBirth, email, PaymentAcctNo) VALUES ('Mr','Test','Test','129','Test Road','Plymouth','PL5 1LL','07855786111','14/04/1930','mr@test.com','123456') I cannot for the life of me figure out what is wrong with this statement. I've ensured all the fields within the database have no validation (this is done within my ASP code) that would stop this statement being inserted. Line 158: dbCommand.Connection = conn;Line 159: conn.Open();Line 160: dbCommand.ExecuteNonQuery();Is the line that brings up the error - I presume this could be either an error in the statement or maybe some settings on the Database stopping the values being added. Any ideas which of this might be ? I'm not looking for someone to solve this for me, just a push in the right direction! Thanks!
View Replies !
Syntax Error Converting Datetime From Character String In Dynamic SQL Statement
Hi, I'm getting the "Syntax error converting datetime from character string." for the below query. I have some request like this query and need to know the correct sql statement for this to avoid this error. use northwind go declare @reqdate datetime ,@shipdate datetime set @reqdate='1996-05-05' set @shipdate='1996-06-05' declare @cmd varchar(1000) set @cmd='select * from orders where requiredate >='+@reqdate+' AND shipdate >='+@shipdate exec @cmd
View Replies !
Select Statement Problem - Group By Maybe Nested Select?
Hey guys i have a stock table and a stock type table and what i would like to do is say for every different piece of stock find out how many are available The two tables are like thisstockIDconsumableIDstockAvailableconsumableIDconsumableName So i want to,Select every consumableName in my table and then group all the stock by the consumable ID with some form of total where stockavailable = 1I should then end up with a table like thisEpson T001 - Available 6Epson T002 - Available 0Epson T003 - Available 4If anyone can help me i would be very appreciative. If you want excact table names etc then i can put that here but for now i thought i would ask how you would do it and then give it a go myself.ThanksMatt
View Replies !
SQL Select Statement To Select The Last Ten Records Posted
SELECT Top 10 Name, Contact AS DCC, DateAdded AS DateTimeFROM NameTaORDER BY DateAdded DESC I'm trying to right a sql statement for a gridview, I want to see the last ten records added to the to the database. As you know each day someone could add one or two records, how can I write it show the last 10 records entered.
View Replies !
SQL Select Statement
I have a database that is constantly being added to... what im trying to do is select the 10 most recent entries EXCEPT for the very most recent. Selecting the 10 most recent is something I can do.... 'select top 10 * from tablename order by id desc' - but how do I leave out the most recent? SQL Server 2005
View Replies !
SELECT Statement
Hi,I'm sorry for the lame question, but I''m a newbie at C#.With the code that follows my signature, I'm trying to retrieve a single value from a table.The query is ok, I've tested manually.But I get the error:"The name userPassword does not exist in the current context".I realize it's a matter of scope, but I need to have the variable value available there.Furthermore, I think that I'm getting no result from the database with my code, because if I put the Response.Write(userPassword) line inside the while cicle, nothing is displayed.Any help would be appreciated.Warm Regards,Mário Gamito--SqlConnection myConn = new SqlConnection("user id=sa" + "password=secret" + "server=192.168.1.4" + "database=workers");try{myConn.Open()}catch (Exception e){Console.WriteLine(e.ToString());}try{SqlDataReader myReader = null;SqlCommand myCommand = new SqlCommand("SELECT password FROM dbo.users WHERE email = 'gamito@foobar.lan'", myConn);myReader = myCommand.ExecuteReader();while(myReader.Read()) { string userPassword = myReader["password"].ToString()); }}catch (Exception e){ Console.WriteLine(e.ToString());}myConn.Close();Response.Write(userPassword);
View Replies !
Max Select Statement
Hi Guys, Having a little problem, can someone take a look at this... Thank You... Trying to get the Max(WebNameTitle) From Max(NumerID) Example code below throws error : I need the Max Value from the Column( WebNameTitle <---nvarchar) and the Max Value from the Column (NumberID <--int) New SqlCommand("Select Max(WebNameTitle) FROM ComBooks WHERE Max(NumberID) = MaxNumberID", conCommerce)
View Replies !
Select Statement In ASP.NET
hello all, I need to SELECT data in my ASP.NET web service from my MSSQLExpress database. I checked to INSERT data into it and it worked well , and here is the code of my insert: 1 <WebMethod()> _2 Public Function SaveNumName(ByVal UserNum As Integer, ByVal UserName As String)3 Dim DS As New SqlDataSource4 5 DS.ConnectionString = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=tstSQL"6 ' DS.ConnectionString = ConfigurationManager.ConnectionStrings("tstSQLConnectionString1")7 DS.InsertCommandType = SqlDataSourceCommandType.Text8 DS.InsertCommand = "insert into tbl1 (number,name) values (@number,@name)"9 DS.InsertParameters.Add("number", UserNum)10 DS.InsertParameters.Add("name", UserName)11 12 DS.Insert()13 14 Return 115 End Function The previous code worked well for the insertion of data, but when I tryed the same technique with the selection of data, it didn't work, and here is my code for the select: 1 <WebMethod()> _2 Public Function GetName(ByVal Number As Integer)3 Dim Name As String4 'Dim ConnStr As String = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=malalation_tstSQL"5 Dim GV As New GridView6 GV.Visible = False7 Dim DS As New SqlDataSource8 DS.ConnectionString = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=tstSQL"9 10 DS.SelectCommandType = SqlDataSourceCommandType.Text11 DS.SelectCommand = "SELECT name from tbl1 where number = 1"12 ' DS.Select()13 GV.DataSource = DS14 Name = GV.Rows(0).Cells(1).Text15 Return Name16 End Function I think that the problem is with storing the result of the SELECT satatement, so what do you think??
View Replies !
Need Help With SELECT Statement
Hi, I have a table (SQL 2000) that holds inside login records of each system. All the systems logging 0-50 times each day. I need to create “Last Login� report that shows as following: SystemID LastLogin System001 2008-04-23 21:14:49 System002 2008-03-12 21:15:06 System003 2008-01-20 22:14:15 System004 2008-04-23 22:14:24 System005 2008-02-23 22:14:42 Need help with SELECT statement Thanks in advance. Alex
View Replies !
|