Parameterized Queries - Works In Access But Not SQLS2k?
Feb 3, 2004
I have an application where users can enter data into any (or all) of 6 search fields,
to produce a filtered query.
This works fine using my Access version(see code below),
but as SQLS2k cannot use "IIF", I tried to replace these bits with
"CASE/WHEN/THEN/ELSE" lines, which does not work with numeric fields
as these cannot be "wild-carded" in the same way as Access allows.
Can anyone suggest a way forward that does not involve coding all the
possible permutations of "SELECT" blocks driven by lots of nested "IF/THEN/ELSE"s?
FROM (((tAudit
LEFT JOIN tCategories
ON tAudit.CategoryID = tCategories.CategoryID)
LEFT JOIN tClients ON tAudit.ClientID = tClients.ClientID)
LEFT JOIN tContracts ON tAudit.ContractID = tContracts.ContractID)
LEFT JOIN tProducts ON tAudit.ProductID = tProducts.ProductID
WHERE (((tAudit.ActionType) Like IIf(IsNull([CurrentType]),"*",[CurrentType]))
AND ((tAudit.ClientID) Like IIf(IsNull([CurrentClientID]),"*",[CurrentClientID]))
AND ((tAudit.ContractID) Like IIf(IsNull([CurrentContractID]),"*",[CurrentContractID]))
AND ((tAudit.ProductID) Like IIf(IsNull([CurrentProductID]),"*",[CurrentProductID]))
AND ((tAudit.CategoryID) Like IIf(IsNull([CurrentCategoryID]),"*",[CurrentCategoryID]))
AND (([tAudit].[DateStamp]) Between [FromDate] And [ToDate]));
HelloWhen I use a PreparedStatement (in jdbc) with the following query:SELECT store_groups_idFROM store_groupsWHERE store_groups_id IS NOT NULLAND type = ?ORDER BY group_nameIt takes a significantly longer time to run (the time it takes forexecuteQuery() to return ) than if I useSELECT store_groups_idFROM store_groupsWHERE store_groups_id IS NOT NULLAND type = 'M'ORDER BY group_nameAfter tracing the problem down, it appears that this is not preciselya java issue, but rather has to do with the underlying cost of runningparameterized queries.When I open up MS Enterprise Manager and type the same query in - italso takes far longer for the parameterized query to run when I usethe version of the query with bind (?) parameters.This only happens when the table in question is large - I am seeingthis behaviour for a table with > 1,000,000 records. It doesn't makesense to me why a parameterized query would run SLOWER than acompletely ad-hoc query when it is supposed to be more efficient.Furthermore, if one were to say that the reason for this behaviour isthat the query is first getting compliled and then the parameters aregetting sent over - thus resulting in a longer percieved executiontime - I would respond that if this were the case then A) it shouldn'tbe any different if it were run against a large or small table B) thisperformance hit should only be experienced the first time that thequery is run C) the performance hit should only be 2x the time for thenon-parameterized query takes to run - the difference in response timeis more like 4-10 times the time it takes for the non parameterizedversion to run!!!Is this a sql-server specific problem or something that would pertainto other databases as well? I there something about the coorect use ofbind parameters that I overall don't understand?If I can provide some hints in Java then this would be great..otherwise, do I need to turn/off certain settings on the databaseitself?If nothing else works, I will have to either find or write a wrapperaround the Statement object that acts like a prepared statement but inreality sends regular Statement objects to the JDBC driver. I wouldthen put some inteligence in the database layer for deciding whetherto use this special -hack- object or a regular prepared statementdepending on the expected overhead. (Obviously this logic would onlybe written in once place.. etc.. IoC.. ) HOWEVER, I would desperatelywant to avoid doing this.Please help :)
Is there a way to use parameterized queries with RDA method? I write a program for WinCE5.0 and when I submit a query I use hardcoded date format and this causes problems in different systems.There's a solution for this?
The above code doesnt work. Firstly I am not sure if I can execute the two statements in one go. Secondly, I am not sure if output parameters are supported.
I have been working with SQL Server since 6.5 but have always used sprocs and am feeling a little lost here without them. Any help getting started would be greatly appreciated.
Hey fellas. Here's my situation. I have two textboxes where the user enters a "start" date and an "end" date. I want to search a table to find records who's "expired" column date is between those two dates provided by the user. The tricky part is, if the user just puts a start date in but no end date, I want it to search from whatever start date the user entered to the future and beyond. Essentially, I think I'm looking for a SQL statement along the lines of: SELECT Request.RequestID, Request.URL, ActionProvider.Name, Request.CurrentStageID, Request.Decision, Request.SubmissionDate, Request.ExpirationDate FROM Request INNER JOIN RequestSpecificActionProvider ON Request.RequestID = RequestSpecificActionProvider.RequestID INNER JOIN ActionProvider ON RequestSpecificActionProvider.ActionProviderID = ActionProvider.ActionProviderID INNER JOIN RoleActionProvider ON ActionProvider.ActionProviderID = RoleActionProvider.ActionProviderID INNER JOIN Role ON RoleActionProvider.RoleID = Role.RoleID WHERE
CASE WHEN @BeginDate is not null AND @BeginDate <> '' THEN Request.ExpirationDate > @BeginDate END
AND
CASE WHEN @EndDate is not null AND @EndDate <> '' THEN Request.ExpirationDate > @EndDate END
AND (Role.Description = 'Requestor')
I realize my code isn't correct and there's still a floating "AND" out there I would have to put some logic around. Anyway, how do I do this? Do I need to build three separate queries in my tableadapter (one for if both dates are provided, one for if start date is provided, one for if end date is provided) and build the logic in my application code or can I tackle it with SQL? If I can tackle it with SQL, where have I gone astray? I'm currently getting the error: "Error in WHERE clause near '>'. Unable to parse query text." Thanks for the help everyone!
How would I debug such a query. I have a sqlCommand to which I add several parameters for an insert statement. if the statement fails, for some reason, I would like to copy the final sql with all values inserted as text and use this in e.g. TOAD to see where the error is coming from. Is this possible?
Hi, I need to use parameters with the IN clause in a SQL statement like: select * from tableX where field IN (1,2,3,4) I don't know how to do that. I'm using SQLServer and OleDB.
when I try and insert something like sp_PRO '123154', 'it's good', '23.23', 1
I can't insert "'" and "," because that is specific to how each item is delimited inorder to insert into the stored procedure. But if I hard code this into a aspx page and don't create a stored procedure I can insert "'" and ",". I have a scenario where I have to use a stored procedure...confused.
know if there is any way out to run execution plan for parameterized queries?
As application is sending queries which are mostly parameterized in nature and values being used are very robust in nature, So i can not even make a guess.
I've been driving myself nuts trying to get a sensible product search going. The existing live site search is just a LIKE %searchterm% on the Title field in our Products table. Fast, but not great ;) Talks between IT and Marketing have resulted in this being the desired results and order:
Exact Title match Substring Title match Substring Keywords match Substring Description match
OK, I can easily do this with UNION queries using LIKE (and a virtual "weight" column in each query), but the query takes too long. So I'm trying out SQL Server full text indexing, in an attempt to get the speed up (and the natural language stuff is just plain cool).
Where I'm running into problems is doing a FULLTEXT match on Description. It seems that to do a phrase match (e.g. "new york" should match only Descriptions where the phrase "new york" occurs) I need to enclose the search term in quotation marks in the query (or maybe single AND double quotes).
But using parameters in ASP.NET (which I'm supposed to do to avoid SQL injection attacks, yes?) I don't really have full control of the quoting - ASP.NET and/or SQL Server automagically quotes strings for me before passing them into the query. I think.
For example, this doesn't find any description matches: ========================================== Declare @theSearchTerm varchar(100), @theSearchTerm1 varchar(100)
set @theSearchTerm = "new york" set @theSearchTerm1 = "%new york%"
SELECT m.TitleCode, m.ShortName, m.ShortDescription, 50 as theWeight FROM Product m(NoLock) WHERE m.ShortName = @theSearchTerm
UNION
(SELECT m.TitleCode, m.ShortName, m.ShortDescription, 40 as theWeight FROM Product m(NoLock) WHERE m.ShortName LIKE @theSearchTerm1)
UNION
(SELECT m.TitleCode, m.ShortName, m.ShortDescription, 30 as theWeight FROM Product m(NoLock) WHERE CONTAINS(*, '"@theSearchTerm"'))
ORDER BY theWeight DESC, m.ShortName ==========================================
But this one (where I put in the actual string instead of using the parameter) *does* get the desired results, including matches in the Description: ========================================== Declare @theSearchTerm varchar(100), @theSearchTerm1 varchar(100)
set @theSearchTerm = "new york" set @theSearchTerm1 = "%new york%"
SELECT m.TitleCode, m.ShortName, m.ShortDescription, 50 as theWeight FROM Product m(NoLock) WHERE m.ShortName = @theSearchTerm
UNION
(SELECT m.TitleCode, m.ShortName, m.ShortDescription, 40 as theWeight FROM Product m(NoLock) WHERE m.ShortName LIKE @theSearchTerm1)
UNION
(SELECT m.TitleCode, m.ShortName, m.ShortDescription, 30 as theWeight FROM Product m(NoLock) WHERE CONTAINS(*, '"new york"'))
ORDER BY theWeight DESC, m.ShortName ==========================================
Trying various permutations of quotes around the parameter gives me either syntax errors or undesirable results.
Has anybody tried this sort of thing? How did you do it?
I've got a popular problem so i get a message that server acces denied! ..
But that what is different in my error.... When i use same setting same database and connection string (on MSDE server) there is no problem...
On SQL server i have got windwos authentication but i added all accounts as ASPNET and SA.... and when i try to connect by
RETTO - name of my server
server=RETTO;uid=sa;pwd=password;database=db1; or by Integrated Security=SSPIserver=RETTO;uid=RETTOASPNET;database=db1;
I CAN BROWSE RECORDS THERE ARE NO PROBLEMS WITH CONNECTION!!! but when i try to update or iinsert or delete something in database there becomame this error that access denied or server does not exist!!!
PLEASE HELP I'm FIGHTING WITH THAT FOR OVER 5 DAYS!!!
I MADE FOR MY ACCOUNTS (SA, ASPNET) ALL THINGS ALLOWED AS EXECUTING stored procedures.. OR ACCESING datatables with insert delete and update query WHERE IS THE PROBLEM!!!??
My organization is planning to upgrade sql server 2000 to sql server 2005. One of the main reason to upgrade, is to utilize new security(encryption) feature provided by the SQL server 2005. Our main aim is to encrypt few columns of the database tables. I am in a dilemma on how to encrypt tables which already has data in it? We have VB application that uses SQL server 2000 as backend. I do not want to change the frontend. Is there any why we could save the data in an encrypted form without changing the frontend??
Help, I had my entire DB created and when i thought i was done, i upsized to SQL and now almost none of my queries work?
The below works when i remove Distinct, but then i have doubles?
Code:
SELECT DISTINCT Equip_ProductName.ProductName, Equip_ProductName.ProductInfoID, Equip_ProductName.ProductDesc, Equip_ProductName.ProductSearchTerm, Equip_ProductName.ProductMore, Equip_ProductName.Visible, Equip_Products.ProductID, Equip_Products.CategoryID FROM Equip_Products INNER JOIN Equip_ProductName ON Equip_Products.ProductInfoID = Equip_ProductName.ProductInfoID WHERE (Equip_ProductName.Visible = 1) AND (Equip_Products.CategoryID = 1) ORDER BY Equip_ProductName.ProductName
I am trying to fill a table from 2 other tables in MS SQL 2000 the structure ::
Table 1 --> Info InfoID Name
Table 2 --> Item InfoID Num Value
TRANSFORM Max(Item.Value) AS MaxValue SELECT Info.Name FROM Info INNER JOIN Item ON Info.InfoID = Item.InfoID WHERE Item.Num In (10,12,15,100) GROUP BY Info.Name PIVOT Item.Num
in ACCESS 2000 it works fine I get a View with 5 columns --> Name,10,12,15,100 but in MS SQL it doesnt work at all
does someone knows how to translate it for MS SQL (the table structures are exactly the same)?
I have written a intranet page that writes some info into a sql database, basically following the 'SQL Server 2005 Express for Beginners' video.When I debug the application from within 'Visual Web Develop 2005 express' it works fine entries are entered into the DB and I can then edit the db using the admin page.But when I host the site using IIS I doesn't work, submissions to the database seem to fail I can see the DB in the admin page but if I try to edit them or delete them it fails. What could I doing wrong could I be missing a setting in IIS? Any ideas??Here's my webconfig if that helps at all: <?xml version="1.0"?><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <connectionStrings> <add name="studentprofilesConnectionString1" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|studentprofiles.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <roleManager defaultProvider="AspNetWindowsTokenRoleProvider" /> <compilation debug="true" defaultLanguage="c#" /></system.web></configuration>
Getting a weird error while trying out a query from Access 2003 on aSQL Server 2005 table.Want to compute the amount of leave taken by an emp during the year.Since an emp might be off for half a day (forenoon or afternoon), havethe following computed field:SessionOff: ([ForenoonFlag] And [AfternoonFlag])The query works fine when there's no criterion on SessionOff.However, when I try to get the records where the SessionOff equals 0, Iget the following error:~~~~~ODBC--call failed. [Microsoft][SQL Native Client][SQL server]Incorrect syntax near the keyword 'NOT'. (#156)~~~~~I checked the SQL of the Access query, but there's no NOT anywhere init:~~~~~SELECT tblWorkDateAttendance.*FROM tblWorkDate INNER JOIN tblWorkDateAttendance ONtblWorkDate.WorkDate = tblWorkDateAttendance.WorkDateWHERE (((([ForenoonFlag] And [AfternoonFlag]))=0) AND((tblWorkDateAttendance.WorkDate)<Date()) AND((Year([tblWorkDate].[WorkDate]))=Year(Date())) AND((Weekday([tblWorkDate].[WorkDate])) Between 2 And 6) AND((tblWorkDate.HolidayFlag)=False));~~~~~What gives?
We have 2 databases ( Guider and Talker ) and we have a WCF service that is logged in with a domain identity.
In our SQL Server we have the service ID added to the Data Server Logins and both Guider and Talker are given access to the user.
When we access Guider we have no problems getting data.
When we access Talker we have a login failure:
Cannot open database 'Talker' requested by the login. The login failed.
Login failed for user 'AcornCommunicationServices'.
The thing that gets me is that the user is created at the Server level, in both Databases, and at the server level both databases are checked for the user. master has been set as the default database for the user.
Basically, as far as I can see Talker and Guider are configured identically! So I cannot figure out why I cannot login to the second database!
Is there a specific setting I'm missing somewhere to grant login access to the user? I'm using
When our production site was deployed on the client's WinServer2003, my webservice is throwing a "server does not exist or access denied" exception. I'm using the same connection string (typed once) as i'm using in my web forms on the user visible sections of the site. the service also works fine on my XP testing machine. unfortunately, I'm not a 2003 admin. If anyone can help, i would greatly appreciate it, trying to find what is misconfigured on the client's server is driving me bonkers.
a while back i had to do a project with an access database, one of the biggest problems i had back then was gettting the primary key of a datarow you had just inserted into the database.
After a long set of trial and error i came up with the following:
- add the tablemappings of a table - call the dataadapte.fillschema method
then after inserting a new row into the database the primary key gets filled in automatically!
now thing is
i was hoping to duplicate this in sql server
but it doesn't seem to work at all
so after i insert a row into my datatable and update it the row is in the database but in vb the datarow primary key is not filled in! anyone have an idea?
prefereabely one that does not resort to stored procedures with return parameters etc
I am runing Windows 2003 which has both SQL2000 and SQL2005.
The following works in 2000 but not 20005
Code Snippet DECLARE @sql nvarchar(4000) set @sql = 'sp_addlinkedserver @server = N''dbAccessPO'', @provider = N''Microsoft.Jet.OLEDB.4.0'', @srvproduct = N''OLE DB Provider for Jet'', @datasrc = N''C:Temppopts.mdb''' exec sp_executesql @sql set @sql = 'sp_addlinkedsrvlogin ''dbAccessPO'', FALSE, ''sa'', ''Admin'', NULL' exec sp_executesql @sql
Running this:
Code Snippetselect * from dbAccessPO...MyTable
Produces this error:
Code Snippet OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "dbAccessPO" returned message "Unspecified error". Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "dbAccessPO".
I have a stored procedure which is run through MS Access (yuck). It does not appear to fail, but it does not populate certain tables, and is also rather complex. I did not write it, and am trying my best to fix it. However, when I run the same procedure with the same parameters from within Management Studio (database state is the same, I restore from backup before trying out each execution) it populates the tables correctly. I have profiled both executions (from MS and from Access) and it is running with the same NTUsername, and thus the same permissions. The process used to work and then some changes were made to the DB which seem to have broken it from Access. As far as I know, the Access code has not changed, although it may have done so. The proc call from Access uses the same parameters, and does not throw an error, although it does not appear to close the connection to the DB (I'm looking into this). Access uses an ODBC connection to connect to SQL Server.
I have this query in a stored procedure. I will simplify it so that it shows the issue I am having.
I have two tables. One table has a PK called PRSubLineID. the other table has that in a foreign key.
I did a query like this using the IN Statement
SELECT PRSubLineID, PRSUBLINENumber, f2, f3, FROM PRSUBLINES PRSL WHERE PRSL.PRSUBLINENumber LIKE '%test%' AND PRSL.PRSubLineID NOT IN (SELECT CSL.PRSUBLineID FROM CtrSubLines CSL)
This is supposed to select those items from one table with a PRSubLineNumber containing the work Test which has a primary key that has not been used as a foreign key in the other table. However I am getting an empty resultset back.
But when I comment out the "And" and end the query after '%test%', Like this:
SELECT PRSubLineID, PRSUBLINENumber, f2, f3, FROM PRSUBLINES PRSL WHERE PRSL.PRSUBLINENumber LIKE '%test%'
I show a resultset containing three records whose PRSubLineID' s are 2384, 2385, 2386.
But when I add this query to the query window:
Select * FROM CtrSubLines CSL WHERE CSL.PRSubLineID in (2384, 2385, 2386)
I also get a null resultset. So hoping to decipher what was going on I changed the initial query to look like this.
SELECT PRSubLineID, PRSUBLINENumber, f2, f3, FROM PRSUBLINES PRSL WHERE PRSL.PRSUBLINENumber LIKE '%test%' AND PRSL.PRSubLineID /*NOT*/ IN (SELECT CSL.PRSUBLineID FROM CtrSubLines CSL)
And this still returned a null result set.
Basically this is saying that my PRSubLineIDs are neither included nor excluded in the set of all values of PRSubLineID in the CtrSubLines table. But that is simply impossible.
HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials. Internet Information Services (IIS)
when I attempt to connect to Reports or ReportServer from my desktop, but it works normally when I login with the same userid and run it directly on the server, using IE. It is prompting me for a login 2 or 3 times before failing.
My configuration is:
Report Server system:
Windows Server 2003 R2 SP2 - 32bit
SQL Server 2005 Reporting Services Enterprise Edition Windows & Web Service run as a domain account Database connection is using domain account - not in db_owner, but in RSExec roles Database is on another server, and is Native, not SharePoint integrated Reports & ReportServer are in a separate application pool Reporting Services had SP2 installed before it was configured The Rport Server is a VM
Database server
Windows Server 2003 R2 SP2 - x64 SQL Server 2005 Enterprise Edition 64bit Version 9.00.3200.00
The Report Manager was not working at all, and I discovered that there was no entry in the .Net Framework version on the APS.Net tab in properties for the Reports virtual directory. I am not seeing any errors or anything unusual in the Event log or in the ReportServer log files.
FrontPage 2002 extensions were installed, and then removed. I noticed that this installed a SharePoint virtual directory, and that disappeared when I removed FrontPage extensions.
The domain group my userid is in is in the local Administrators group on the ReportServer system, and I have added this group as a System Administrator and Content Manager through the report Manager.
Hello all, Does anyone know of a utility to migrate Access 97 Queries to SQL Server 7? I've over 400 of them and I am trying not to have to do them by hand.
Also I tried to use to migration wizard from MS instead of the DTS and all I got was Error after error. 'Invalid Date/Time', 'Error with YES/NO field' and 'Timed out' were the most common. In the end only 4 tables out of 89 were migrated.
How this can be ONE SQL Query?In query designer on access theleft table is TITLES_IN_OFFICES_qry and the table on the right isTITLOC.I have never used a query as a table before in a select .
I am wondering if anyone can recommend a basic, "How To" article, column or book for someone who has never worked with Access but is familiar with DB programming.
I need to know how to submit queries, and print reports.
I have an Access database that used to produce a mass of Performance Indicators from Access tables. The data is now held on SQL Server and I run the Access queries from the SQL tables. I wouldlike to move all the queries over to SQL but not sure if I can do that. Here's an example of one of the queries (the SQL view)
SELECT tblCalls.* FROM tblCalls WHERE (((tblCalls.Call_date)>=[Forms]![ReportParams]![SDate] And (tblCalls.Call_date)<=[Forms]![ReportParams]![EDate]) AND ((tblCalls.NotAccepted)=False) AND ((tblCalls.Completed_time) Is Not Null) AND ((tblCalls.Category)="fly tipping"));
SELECT Month([Call_date]) AS Mnth, DateSerial(Year([Call_date]),Int((Month([Call_date])-1)/3)*3+4,0) AS Qtr, Sum(Work_Days([Call_date],[Completed_time])) AS RespTime, Sum(1) AS Count, Sum(Work_Days([Call_date],[Completed_time]))/[Count] AS AvgTime FROM qryFlyTippingStatsSummary1 GROUP BY Month([Call_date]), DateSerial(Year([Call_date]),Int((Month([Call_date])-1)/3)*3+4,0) ORDER BY Month([Call_date]), DateSerial(Year([Call_date]),Int((Month([Call_date])-1)/3)*3+4,0);
I am using SQL2005 (Installed on VISTA). It was running smoothly until today....for some reason I cannot access any tables in queries that I try to run in Management Studio. I can open the tables and see the information, but all queries I try to run result in the following error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'DBO.BEYLEVEL16'.
I tried to run simple select queries on other tables but I get the same error message. Do not understand, eveything was working fine yesterday.
I'm working on an electronic register which people use to sign in and out of a building. It uses 3 tables, one to store personal information (Name & Visitor Number), one to store what time they come in, and one to store what time they leave. Visitor Number is the primary key in the Visitor_Info table, and is used as a foreign key in the other 2 tables.
I've been asked to put in an 'emergency print' function where, when you click the print button, it compares the data in the time in database and the time out database and prints a list of people still in the building.
So, what I'm trying to do is create a SQL query that will give me this information. Having never used SQL before, it's a little tricky. I've spent the last few days looking at tutorials on the net and learning about queries and this is what I've come up with:
Select Time_In_Table.Visitor_Number Not Union Select Time_Out_Table.Visitor_Number
If I'm right (and I'm probably not), this will give me the people who are in the time in table, but not in the time out table.
Can someone please help me by letting me know what I'm doing wrong in the statement above, and also, advise me as to where it goes since none of the tutorials I've found cover where to put the statement in my programming? At a guess, I'd say it goes in the print button click function.