Syntax Headache!!!

Mar 13, 1999

I need to get this statement to run.

Declare @MiD datetime

-- The ATime is a datetime field in the table
-- @OrderBy is an input Parameter also, as is @MiD

SELECT @Statement = 'SELECT tblAudit.* FROM tblAudit WHERE ATime >= ' + @MiD + ' ORDER BY ' + @OrderBy
EXECUTE(@Statement)

@Statement then contains:

SELECT tblAudit.* FROM tblAudit WHERE ATime >= Mar 10 1999 ORDER BY Access_ID

I need the quotes around the Mar 10 1999.

Thanks for the help

View 2 Replies


ADVERTISEMENT

Can Anyone Help Me With This? It's Giving Me A Bad Headache!

Mar 9, 2005

Hi All,

I have a table called Prizes. Here's how it looks in design view with some value placed inside for Illustration purposes.

PrizeID 1, 2, 3, 4, 5
PromotionID 1, 1, 1, 2, 1
PrizeName 10 Cash, 5 cash, 10 cash, 15 cash, 20 cash

My challenge is that I need to write a stored procedure for example, that will find the PrizeID associated with the 4th count of the PromotionID that equals 1 . So in this example, counting to the 4th PromotionID that equalls 1 give us a PrizeID of 5.

I hope I've made myself clear! Can anyone write out a mini SP on how to do this.

Many many thanks in advance,
Brad

View 2 Replies View Related

SQL Query Headache

Jun 24, 2004

Hallo

I am interrogating the structure of SQL Server database looking for the occurence of a particular phrase in the object names/definitions. This is in preparation for decommission/replacement...

When I run the script below in SQL Query Analyzer it returns about 200 results, but when I run the same query in my Access VBA code it returns much less!

SQL Script:
SELECT
so.ID,
so.name,
so.type,
CHARINDEX('insita',so.name) AS PosInObjName,
CASE WHEN CHARINDEX('insita',so.name) > 0 THEN 1 ELSE 0 END AS FoundInObjName,
CHARINDEX('insita',sc.text) AS PosInObjDef,
CASE WHEN CHARINDEX('insita',sc.text) > 0 THEN 1 ELSE 0 END AS FoundInObjDef
FROM
sysobjects so INNER JOIN syscomments sc on so.id = sc.id
ORDER BY [name]

VB Code:
Sub InterrogateDatabaseStructure(sServer As String, sDB As String, sSearch4 As String)
On Error GoTo err_IDS
Dim oCnn As ADODB.Connection
Dim oCmd As ADODB.Command
Dim oRs As ADODB.Recordset
Dim sSQL As String

Set oCnn = New ADODB.Connection
oCnn.ConnectionString = "driver={SQL Server};server=" & sServer & ";uid=;pwd=;database=" & sDB & ";dsn=;"
oCnn.Open

CurrentDb.Execute "DELETE * FROM PhraseSearchResults"
CurrentDb.Execute "DELETE * FROM PhraseInObjName"

Set oCmd = New Command
oCmd.ActiveConnection = oCnn
oCmd.CommandType = adCmdText
sSQL = "SELECT so.ID, so.name, so.type, "
sSQL = sSQL & "CASE WHEN CHARINDEX('" & sSearch4 & "',so.name) > 0 THEN 1 ELSE 0 END AS FoundInObjName,"
sSQL = sSQL & "CHARINDEX('" & sSearch4 & "',so.name) AS PosInObjName, "
sSQL = sSQL & "CASE WHEN CHARINDEX('" & sSearch4 & "',sc.text) > 0 THEN 1 ELSE 0 END AS FoundInObjDef, "
sSQL = sSQL & "CHARINDEX('" & sSearch4 & "',sc.text) AS PosInObjDef "
sSQL = sSQL & "FROM " & sDB & ".dbo.sysobjects so INNER JOIN syscomments sc on so.id = sc.id"

oCmd.CommandText = sSQL
Set oRs = oCmd.Execute()

With oRs
If Not .EOF And Not .BOF Then
.MoveFirst
Do Until .EOF
sSQL = "INSERT INTO PhraseSearchResults VALUES('"
sSQL = sSQL & .Fields(0) & "','" & .Fields(1) & "','" & .Fields(2) & "',"
sSQL = sSQL & .Fields(3) & "," & .Fields(4) & ")"
CurrentDb.Execute sSQL
.MoveNext
Loop
End If
End With


Set oCmd = Nothing
Set oCnn = Nothing

Exit Sub

err_IDS:
MsgBox "Error: " & Err.Description & vbCr & "Error Code: " & Err.Number
Screen.MousePointer = 0
End Sub

Can anyone please advise what I am doing wrong? Thanks.

View 1 Replies View Related

Date Headache

Dec 5, 2005

Guys
I have a table 1 row, a start and end date of a period

create table xperiod(startdate datetime , enddate datetime)
insert xperiod (startdate , enddate)
values ('2004-04-01 00:00:00.000' , 2012-03-31 00:00:00.000)

I'm trying to retrieve a batch of 'smaller' periods from this where the relevant period is a number (of months) passed as a parameter (only ever 1, 3 or 6)


for example, if the parameter is 1 I will obtain the following rows each being a 1 month period starting at the xperiod.startdate value up to an end date of the xperiod.enddate value
startperiod endperiod
'2004-04-01 00:00:00.000' '2004-04-30 00:00:00.000'
'2004-05-01 00:00:00.000' '2004-05-31 00:00:00.000'
'2004-05-01 00:00:00.000' '2004-05-31 00:00:00.000'

and so on to
'2012-03-01 00:00:00.000' '2012-03-31 00:00:00.000'


if the parameter is 3 I will obtain the following rows each being a 3 month period starting at the xperiod.startdate value up to an end date of the xperiod.enddate value


startperiod endperiod
'2004-04-01 00:00:00.000' '2004-06-30 00:00:00.000'
'2004-07-01 00:00:00.000' '2004-09-30 00:00:00.000'
'2004-10-01 00:00:00.000' '2004-12-31 00:00:00.000'

and so on to
'2012-01-01 00:00:00.000' '2012-03-31 00:00:00.000'

Hope this makes sense !

I think I'll be ok on the logic for the while loop but my main problem is getting the endperiod value based on the startperiodvalue
Thx in advance

View 2 Replies View Related

'MSDASQL' Headache

Aug 10, 2006

Hello - hope this is in the right group:We have just started with linked servers and have successfully createda view on SQL Server linked to a Progress database. I can query thisview happily in Query Analyzer.I have created an ASP.NET application to display this view in adatagrid but I get the following error:System.Data.SqlClient.SqlException: OLE DB provider 'MSDASQL' reportedan error. at System.Data.SqlClient.SqlConnection.OnError(SqlExc eptionexception, Boolean breakConnection) atSystem.Data.SqlClient.SqlInternalConnection.OnErro r(SqlExceptionexception, Boolean breakConnection) atSystem.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObjectstateObj) at System.Data.SqlClient.TdsParser.Run(RunBehaviorrunBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)at System.Data.SqlClient.SqlDataReader.ConsumeMetaDat a() atSystem.Data.SqlClient.SqlDataReader.get_MetaData() atSystem.Data.SqlClient.SqlCommand.FinishExecuteRead er(SqlDataReader ds,RunBehavior runBehavior, String resetOptionsString) atSystem.Data.SqlClient.SqlCommand.RunExecuteReaderT ds(CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Booleanasync) atSystem.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Stringmethod, DbAsyncResult result) atSystem.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Stringmethod) atSystem.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehaviorbehavior, String method) atSystem.Data.SqlClient.SqlCommand.ExecuteDbDataRead er(CommandBehaviorbehavior) atSystem.Data.Common.DbCommand.System.Data.IDbComman d.ExecuteReader(CommandBehaviorbehavior) at System.Data.Common.DbDataAdapter.FillInternal(Data Setdataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords,String srcTable, IDbCommand command, CommandBehavior behavior) atSystem.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32startRecord, Int32 maxRecords, String srcTable, IDbCommand command,CommandBehavior behavior) atSystem.Data.Common.DbDataAdapter.Fill(DataSet dataSet) at...The code in my ASP.NET application looks fine and works on non-linkedviews on the same server. Do I need to add a command or change asetting on SQL Server?

View 2 Replies View Related

Beta Headache

May 3, 2006

Hi Folks,

I'm still using the the SQL Server 2005 June CTP to develop. I'm working for a client that intends to upgrade, but has not done so yet. We believed that we had 365 days from the date of installation before it would expire (late July). But Visual Studio 2005 Beta 2 just expired, which is used by SQL Server Business Intelligence Development Studio, so now we can no longer develop SSIS packages or Reporting Services reports.

What can I do?

I thought that maybe installing Visual Studio 2005 express might work, but when I went there, it seems that it is split up into modules (e.g. Visual Basic 2005 express, Visual C++ express, etc...). I don't know if just one of these would be sufficient and if so, which one. Even if it would, it says I'll need to completely remove the SQL Server 2005 beta, as well as the Visual Studio 2005 beta, and I think the .net framework.

My contract is up at the end of June, and it was understood that the client was going to take care of the upgrade. Is there a quick fix here? What can I do with minimal effort? (I don't really have time to wait for the client to get the upgrade approved and done. I know, sniff, sniff! lol.)

View 1 Replies View Related

Object Ownerships Headache

Dec 10, 2005

This is more of an SQL server question than ASP.net.
A stored proc named MyStoredProc is created by admin account (sa) thus the owner of that proce is dbo.
When I log in to the database (Query Analyzer) as another login say User1, I can not use that stored proc since it was owned by sa. I get an error 'Invalid Object Name' or Object does not exist.
If I use the proper name qualifier like dbo.MyStoredProc, It works in the Query analyzser.
The problem I am facing is - My stored procedures, Views, Tables  were created by sa on the development machine. Now its time for deployment. On the deployment machine, I am not the sa. I just belong to the db_Owner role. I have to log in as User1 and not as sa.  In my c# code I have called the stored procedure as MyStoredProc. I get an error 'MyStoredProc does not exist' since I am loging in as User1 and not sa. In order to use the code, I have to change the ownership to this (and all other objects) to User1.
Is that the only way out or I am doing something wrong/missing someting? Your coments/opinions/suggestions welcome.
 

View 1 Replies View Related

Help Constructing A Headache Query...

Sep 28, 2005

I have two tables, both with phone numbers and call times.

one is for incoming calls, one for outgoing calls.

I need to find all phone numbers from the incoming calls table where the number of calls exceeds 100 within the last 30 days, where the last call was within the last 15 mins, and where the number does Not exist in the outgoing call table within the last 30 days.

so far I have this...
(call record is the incoming, callout is the outgoin)

I believe this is giving me all records in the call record table that are within the last month, and not in the outgoing call table OR have not ben called within the last month..

SELECT cr.cli,min(cr.starttime)as "first call",max(cr.starttime)as "last call",count(cr.cli) as "number of calls"
FROM callrecord cr
LEFT JOIN callout co
ON cr.cli = co.cli
where (co.cli is null or datediff(dy,co.calltime,getdate())>30 )
and datediff(dy,cr.starttime,getdate())>30
group by cr.cli
order by cr.cli


i need to add in the 15 minute call check, and also only return those with a count of > 100

can anyone assist? i'm getting a headache :D

tia

a

View 4 Replies View Related

Group By, Creating A Headache

Oct 12, 2006

I am using SQL server 2000.
While using query analyzer I am facing problem.
If a query has group by clause and if that query is not fetching any record (i.e. query is returning nothing), then in this situation, I want zero to be displayed where datatype of field is integer and "-" if datatype of field is varchar.

Please give me solution as soon as possible, a kind request.

Facing problem for the below mentioned query:-

select IsD.ItemCode,
case
when sum(IsD.IssuedQty) is null then 0
else sum(IsD.IssuedQty)
end as IssuedToday
from Inv_IssueMaster IsM, Inv_IssueDetail IsD
where IsM.IssueNo=IsD.IssueNo
group by IsD.ItemCode

In the above mentioned query, datatype of IssuedQty is int and for ItemCode it's varchar.

View 14 Replies View Related

Snapshot Replication Headache

Jan 4, 2006

Hello,
Harry Half wit here!!
I know that snapshot replication is the simplest form of syncing with SQL server and I can't even figure that out today!!.
I keep getting myself confused as to who should be configured to be a publisher, distibutor or subscriber etc etc.
My scenario is simple:
1 server creating a daily snapshot of a table and then 1 remote laptop (msde) pulls the snapshot into it's own database.
Heres what i did so far;
I configured the server to be a publisher and distributor (is that right?) and didn't set up any subscribers because i want to do that from my remote.
From the remote I did nothing but go into EM tools"create new pull subscription" but I cannot see the publication on the server.

SHould I set my remote to be a distributor to do this?

any help very much appreciated!!

View 1 Replies View Related

Reporting Express Headache

Oct 12, 2006

hi all,

i am having a hell of a time trying to understand how im supposed to use the reporting services integrated with sql server 2005 express - advanced. i have searched high and low throughout vb 2005 express for the relevant controls, and i have searched the management studio trying to find the relevant information. there is no reporting server anywhere that i can see. i simply installed the sqlexpr_adv.exe and assumed that all the relevant features would be automatically installed. i cant find them anywhere (also something about a business intelligence thing? also missing). i would be extremely grateful if somebody could help me

regards

adam

View 2 Replies View Related

DateTime Param For SP Causing BIG Headache...!!

Aug 8, 2006

I've got a stored procedure and one of the parameters is a DateTime.  But no matter what I do to the string that's passed into the form for that field, it doesn't like the format.  Here's my code: SqlConnection conn = new SqlConnection(KPFData.getConnectionString());
SqlCommand cmd = new SqlCommand("KPFSearchName", conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = cmd.Parameters.Add("@DOB", SqlDbType.SmallDateTime);
param.Direction = dir;
param.Value = txtDOB.Text;

// also have tried this:

param.Value = Convert.ToDateTime(txtDOB.Text);

// and

param.Value = Convert.ToDateTime(txtDOB.Text).ToShortDateString;

No matter what I do I always get a formatting error - either I can't convert the string to a DateTime, or the SqlParameter is in the incorrect format, or something along those lines.  I've spent a couple hours on this and hoping someone can point out my obvious mistake here...??Thanks for your help!!eddie

View 5 Replies View Related

Subquery Headache With Count And GroupBy

Nov 23, 2005

I'm trying to return an integer from the following table that returnsthe number of unique cities:tblEmployeesName CityJohn BostonFrank New YorkJim OmahaBetty New YorkThe answer should be 3.DECLARE @EmployeeCities intSELECT @EmployeeCities = SELECT ... ???How go I return one row/column into @EmployeeCities from a Count and aGroupBy?Headache already... Maybe it's too early...

View 3 Replies View Related

Linked Server Headache (Access)

Aug 13, 2007

There seems to be a lot of confusion around the groups about linkingto an Access mdb with the SQL Server Jet OLE DB provider and I haventbeen able to find a straight forward solution. Basically, I have anAccess MDB (A2K) on one server and a SQL Server DB (2005 std ed.) onanother - Both on the same network. I'm trying to create a linkedserver object in the SQL server to view data in the mdb. I've set itup and it works - but only from the server machine itself. If you tryto connect the the linked server from any other computer on thenetwork you get the usual access denied / file in use error.The fact that I can use the linked server from the server box itselfbut not from another pc on the network makes me think that it may be apermissions problem. But I am logging in with full Admin rights andstill no joy. Also there is no workgroup security on the mdb, so thatsnot the problem. I've used the surface editor to remove anyrestrictions that may cause problems, OLE DB connect, OPENROWSET etc.but still no joy.I've tried mapping the mdb's location on the server so I could use astandard filepath, rather than a //Server-Name/... path. Again, worksfrom the server, but not from any client PCs, so no joy there either.In frustration, I copied the mdb to the same server and viola - fullaccess to the linked server from anywhere. But this is no good, I needthe mdb file to stay where it is. An mdb full of linked tables wontwork... they don't show up in the linked server.So that's it - out of ideas! Am I just going to have to accept thatlinked server objects are limited just to mdb files on the same servermachine, or is there something I'm missing??? Firewalls, servicelogins, server settings.... something one of you gurus out there knowabout that might be the key to making my headache go away!!!Any input gratefully recieved!!!

View 1 Replies View Related

Index Tuning Wizard - Headache

Jul 20, 2005

Hi,I am having problems getting anything useful out of the index tuningwizard.I have created a table and inserted data into it. When i run the indextuning wizard i expect 2 indexes to be recommended so the book says(Index011 with a key on the uniqueid column and a non clustered indexnamed table02 with a key on the col03 and LongCol02)Instead i get nothing being recommended.What am i doing wrong????Please helpMaryamif exists (select name from dbo.sysobjects where name ='table01' andtype ='u')drop table table01create table table01(uniqueid int identity, longcol02 char(300)DEFAULT 'THIS IS THE DEfault column',col03 char(1))godeclare @counter intset @counter =1while @counter<=1000begininsert table01 (col03) values('a')insert table01 (col03) values('b')insert table01 (col03) values('c')insert table01 (col03) values('d')insert table01 (col03) values('e')insert table01 (col03) values('f')set @counter=@counter+1end

View 3 Replies View Related

VERY Large Binary Import/export Headache

Oct 13, 2006

Hi,

I am currently importing (and exporting) binary flat files to and from Db fields using the TEXTPTR and UPDATETEXT (or READTEXT for export) functions. This allows me to fetch/send the data in manageable packet sizes without the need to load complete files into RAM first.

Given that some files can be up to 1Gb in size I am keen to find out a new way of doing this since the announcement that TEXTPTR, READTEXT and UPDATETEXT are going to be removed from T-SQL.

I had a quick foray into SSIS but couldn't find anything suitable which brings me back to T-SQL. If anyone knows a nice elegant way of doing this and is prepared to share, that would be grand.

Thanks for your time,
Paul

View 9 Replies View Related

Incorrect Syntax Near The Keyword CONVERT When The Syntax Is Correct - Why?

May 20, 2008

Why does the following call to a stored procedure get me this error:


Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'CONVERT'.




Code Snippet

EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'




The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.

I can't find anything wrong in the syntax for CONVERT or any nearby items.


Help me please. Thank you.

View 7 Replies View Related

Incorrect Syntax When There Appears To Be No Syntax Errors.

Dec 14, 2003

I keep receiving the following error whenever I try and call this function to update my database.

The code was working before, all I added was an extra field to update.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'


Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)

Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String
Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String

strProjectName = CType(e.Item.FindControl("txtProjectName"), TextBox).Text
txtProjectDescription = CType(e.Item.FindControl("txtProjDesc"), TextBox).Text
strProjectState = CType(e.Item.FindControl("txtStatus"), TextBox).Text
intEstDuration = CType(e.Item.FindControl("txtDuration"), TextBox).Text
dtmCreationDate = CType(e.Item.FindControl("txtCreation"),TextBox).Text
strCreatedBy = CType(e.Item.FindControl("txtCreatedBy"),TextBox).Text
strProjectLead = CType(e.Item.FindControl("txtLead"),TextBox).Text
dtmEstCompletionDate = CType(e.Item.FindControl("txtComDate"),TextBox).Text
intProjectID = CType(e.Item.FindControl("lblProjectID"), Label).Text

Dim strSQL As String
strSQL = "Update tblProject " _
& "Set strProjectName = @strProjectName, " _
& "txtProjectDescription = @txtProjectDescription, " _
& "strProjectState = @strProjectState, " _
& "intEstDuration = @intEstDuration, " _
& "dtmCreationDate = @dtmCreationDate, " _
& "strCreatedBy = @strCreatedBy, " _
& "strProjectLead = @strProjectLead, " _
& "dtmEstCompletionDate = @dtmEstCompletionDate, " _
& "WHERE intProjectID = @intProjectID"

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring"))
Dim cmdSQL As New SqlCommand(strSQL, myConnection)

cmdSQL.Parameters.Add(new SqlParameter("@strProjectName", SqlDbType.NVarChar, 40))
cmdSQL.Parameters("@strProjectName").Value = strProjectName
cmdSQL.Parameters.Add(new SqlParameter("@txtProjectDescription", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@txtProjectDescription").Value = txtProjectDescription
cmdSQL.Parameters.Add(new SqlParameter("@strProjectState", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@strProjectState").Value = strProjectState
cmdSQL.Parameters.Add(new SqlParameter("@intEstDuration", SqlDbType.NVarChar, 60))
cmdSQL.Parameters("@intEstDuration").Value = intEstDuration
cmdSQL.Parameters.Add(new SqlParameter("@dtmCreationDate", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@dtmCreationDate").Value = dtmCreationDate
cmdSQL.Parameters.Add(new SqlParameter("@strCreatedBy", SqlDbType.NVarChar, 10))
cmdSQL.Parameters("@strCreatedBy").Value = strCreatedBy
cmdSQL.Parameters.Add(new SqlParameter("@strProjectLead", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@strProjectLead").Value = strProjectLead
cmdSQL.Parameters.Add(new SqlParameter("@dtmEstCompletionDate", SqlDbType.NVarChar, 24))
cmdSQL.Parameters("@dtmEstCompletionDate").Value = dtmEstCompletionDate
cmdSQL.Parameters.Add(new SqlParameter("@intProjectID", SqlDbType.NChar, 5))
cmdSQL.Parameters("@intProjectID").Value = intProjectID

myConnection.Open()
cmdSQL.ExecuteNonQuery
myConnection.Close()

MasterList.EditItemIndex = -1
BindMasterList()


End Sub

Thankyou in advance.

View 3 Replies View Related

Which Is Faster? Conditional Within JOIN Syntax Or WHERE Syntax?

Mar 31, 2008

Forgive the noob question, but i'm still learning SQL everyday and was wondering which of the following is faster? I'm just gonna post parts of the SELECT statement that i've made changes to:

INNER JOIN Facilities f ON e.Facility = f.FacilityID AND f.Name = @FacilityName

OR

WHERE f.Name = @FacilityName


My question is whether or not the query runs faster if i put the condition within the JOIN line as opposed to putting in the WHERE line? Both ways seems to return the same results but the time difference between methods is staggering? Putting the condition within the JOIN line makes the query run about 3 times faster?

Again, forgive my lack of understanding, but could someone agree or disagree and give me the cliff-notes version of why or why not?

Thanks!

View 4 Replies View Related

Converting Rrom Access Syntax To Sql Syntax

Sep 23, 2007


Ok I am tying to convert access syntax to Sql syntax to put it in a stored procedure or view..
Here is the part that I need to convert:

SELECT [2007_hours].proj_name, [2007_hours].task_name, [2007_hours].Employee,
IIf(Mid([task_name],1,3)='PTO','PTO_Holiday',
IIf(Mid([task_name],1,7)='Holiday','PTO_Holiday',
IIf(Mid([proj_name],1,9) In ('9900-2831','9900-2788'),'II Internal',
IIf(Mid([proj_name],1,9)='9900-2787','Sales',
IIf(Mid([proj_name],1,9)='9910-2799','Sales',
IIf(Mid([proj_name],1,9)='9920-2791','Sales',

)
)
)
)
) AS timeType, Sum([2007_hours].Hours) AS SumOfHours
from................

how can you convert it to sql syntax

I need to have a nested If statment which I can't do in sql (in sql I have to have select and from Together for example ( I can't do this in sql):
select ID, FName, LName
if(SUBSTRING(FirstName, 1, 4)= 'Mike')
Begin
Replace(FirstNam,'Mike','MikeTest')
if(SUBSTRING(LastName, 1, 4)= 'Kong')
Begin
Replace(LastNam,'Kong,'KongTest')
if(SUBSTRING(Address, 1, 4)= '1245')
Begin
.........
End
End

end




Case Statement might be the solution but i could not do it.






Your input will be appreciated

Thank you

View 5 Replies View Related

Multiple Left Joins (2 Left Joins 1 Big Headache)

Sep 1, 2005

Hi All,

Im having a problem with a statement i cannot seem to get 2 left joins working at the same time 1 works fine but when i try the second join i get this error:-

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'

[Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx'.


My SQL statment is as follows :-
SELECT children_tutorial.*,schools.schoolname,regions.rname FROM children_tutorial LEFT JOIN schools ON children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx

I am using an Access database i have tried all sorts to get it working and its driving me mad!! any help would be really appreciated.

View 2 Replies View Related

Incorrect Syntax Near The Keyword 'from'. Line 1: Incorrect Syntax Near ')'.

May 27, 2008

This is the error it gives me for my code and then it calls out line 102.  Line 102 is my  buildDD(sql, ddlPernames)  When I comment out this line the error goes away, but what I don't get is this is the same way I build all of my dropdown boxes and they all work but this one.  Could it not like something in my sql select statement.  thanksPrivate Sub DDLUIC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DDLUIC.SelectedIndexChanged
Dim taskforceID As Byte = ddlTaskForce.SelectedValueDim uic As String = DDLUIC.SelectedValue
sql = "select sidstrNAME_IND from CMS.dbo.tblSIDPERS where sidstrSSN_SM in (Select Case u.strSSN from tblAssignedPersonnel as u " _
& "where u.bitPresent = 1 and u.intUICID in (select intUICID from tblUIC where intTaskForceID = " & taskforceID & " and strUIC = '" & uic & "'))"ddlPerNames.Items.Add(New ListItem("", "0"))
buildDD(sql, ddlPerNames)
 
End Sub

View 2 Replies View Related

Incorrect Syntax Near The Keyword 'SELECT'.Incorrect Syntax Near The Keyword 'else'.

May 22, 2008

What I am trying to create a query to check, If recDT is not value or null, then will use value from SELECT top 1 recDtim FROM Serv. Otherwise, will use the value from recDT. I have tried the below query but it doesn't work. The error says, Incorrect syntax near the keyword 'SELECT'.Incorrect syntax near the keyword 'else'.1 SELECT
2 case when recDT='' then SELECT top 1 recDtim FROM Serv else recDT end
3 FROM abc
4
Anyone can help? Thanks a lot.

View 5 Replies View Related

SQL Syntax

Apr 2, 2007

Hi, i am trying to write a mulitple sql statement. basically i have 5 fields to search:

User ID
FirstName
LastName
Department
Site
i would like to search the records of the database with any of the fields above, so a user can specify a last name of "smith" and a department of "finance" which would return all the smiths in the finance department. or if a user enters "john" all the johns from any department or site would appear. How would the sql statement go like for this? and could i bind a tableadapter to a datagrid to view the results? 
 Any help would be appreciated. Thank you.

View 7 Replies View Related

Syntax

Aug 8, 2007

cmd.CommandText="Insert INTO personaldet(Firstname,Lastname,Username,password,dob,) values '('"+txtfname.Text.Replace("'", "''").ToString()+"','"+txtlname.Text+"','"+txtusername.Text+"','"+txtpassword.Text+"','"+txtdob.Text+"')'";
 
always says syntax error ')'.
check this plz
 

View 4 Replies View Related

Help With C# Syntax

Nov 11, 2007

Hello, I have at sp that return a value:set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_getLastActivityDate]
(
@userid nvarchar(256)
 
)
AS
DECLARE @ret nvarchar(256)
SET @ret = (SELECT CAST(LastActivityDate AS nvarchar)
FROM aspnet_Users
WHERE UserName = @userid)
RETURN @ret
 The sp returns a nvarchar. How can i write the syntax in C# to grab the value in @ret?
// Tomas

View 2 Replies View Related

Bad Syntax

Feb 24, 2004

I just cannot get the syntax right for this: (The problem is in my TSart and TEnd)

Dim SQL As String = "Select DateEntered FROM tblTasks Where [DateEntered] Between " '" & TStart & "'" And "'" & TEnd & "'" And [ID] = " & _
IDSent

Thank you for any help,

View 1 Replies View Related

Help With LIKE Syntax...

May 17, 2004

HI All,

I am writing some code where i want to get a list of all the company names that start with say, M...

here is what i have:



Dim M_company, companyID_M

Set M_company = adoCon.Execute("SELECT company FROM tbl_exib WHERE company LIKE 'm%'")
companyID_M = M_company( 0 )



but this is only returning the first company in the list that starts with M. Can anybody help with getting it to return more than one value???

thanks,
Leissa

View 4 Replies View Related

SQL Syntax Help

Jan 6, 2005

I'm a 3GL guy not familiar with SQL that much. What I try to add a record to shopping cart and assign a line number for each record. If the same item already exist, instead of adding a new line I'd like to add to existing line. I use to following code and I got two lines created even I was only adding the very first first. The following are the code I wrote, would anyone please give some hints. Thx.

ALTER PROCEDURE dbo.AddItemToCart
(
@Cart nvarchar(50),
@ItmID int,
@Qty int,
@ItmTyp char
)
As

Declare @AllItmCount Int
SELECT
@AllItmCount = Count(ItmID)
FROM
ShoppingCart
WHERE
Cart = @Cart

IF @AllItmCount = 0 /*new shoppong cart*/
INSERT INTO ShoppingCart
( Cart, Qty, ItmID, ItmTyp, Line )
VALUES
( @Cart, @Qty, @ItmID, @ItmTyp, 1)

ELSE /*some item entered */

DECLARE @CountItems int

SELECT
@CountItems = Count(ItmID)
FROM
ShoppingCart
WHERE
ItmID = @ItmID AND Cart = @Cart AND ItmTyp='R'

IF @CountItems > 0 /* same item entered before then add together */

UPDATE ShoppingCart
SET Qty = (@Qty + ShoppingCart.Qty)
WHERE ItmID = @ItmID AND Cart = @Cart AND ItmTyp='R'

ELSE /* Find the last line number */

Declare @LastLine Int
SELECT @LastLine = Max(Line)
FROM ShoppingCart
WHERE Cart = @Cart

/*Add a new line */

INSERT INTO ShoppingCart
(Cart, Qty, ItmID, ItmTyp, Line)
VALUES
(@Cart, @Qty, @ItmID, @ItmTyp, @LastLine + 1)

View 6 Replies View Related

Help With SQL Syntax

Apr 23, 2005

Hi all,
I'm trying to build a simple forum. I want to display a list containing the forum names and last post date and last post author. I can view the date, but can't figure out a way to see the author. Here's the query i use:
SELECT     ForumID, ForumTitle, ForumDesc, ForumTopics, ForumReplies,                          (SELECT     MAX(AddedDate)                             FROM          (SELECT     ForumID, AddedDate, Author                                                    FROM          dbo.Forums_Topic                                                    UNION ALL                                                    SELECT     ForumId, AddedDate, Author                                                    FROM         dbo.Forum_Reply) AS dates                            WHERE      (ForumID = dbo.Forums.ForumID)) AS ForumLastPostDateFROM         dbo.Forums
Any suggestion on how to show the author of the last message as well? Thanks in advance.

View 27 Replies View Related

Sql Syntax?

Dec 6, 2005

i want to find some repeatable data in a column,is there a sql syntax here?Thanks in advance.

View 1 Replies View Related

Syntax ?

Jan 7, 2002

Hello,

I am trying to create a view, but I am having trouble with the syntax (go figure!). It seems that as I reference more and more tables, my result set becomes smaller. For example, I want to return the state for all my customers then everything is fine, but when I want the state plus the site type (home, office, etc.) then I return fewer results. What is would be the correct syntax to use to return all the rows even if some of the columns have NULL?

SELECT TimeZone.LongZone, SiteMain.SiteNumber,
SiteType.SiteTypeDescription
FROM SiteType INNER JOIN
TimeZone ON SiteType.id = TimeZone.id INNER JOIN
SiteMain ON TimeZone.id = SiteMain.TimeZone AND
SiteType.id = SiteMain.SiteType

View 1 Replies View Related

If Else Syntax

Feb 5, 2002

Can someone help me with the syntax for an if else statement such as:

select (if column(a) > 1) then print '+' else print '-')
,column(b)
,column(c)
,etc.
from table...

BOL doesn't seem to be much help for this
Thanks in advance!
CP

View 1 Replies View Related







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