What Is The OrElse && Keyword In SQL?
Jan 28, 2008and how do I write an if phrase?
Shimi
and how do I write an if phrase?
Shimi
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.
I am trying to pass several ids to use in a where clause. 1 For Each row as GridViewRow In gv_child.Rows
2 If row.RowType = DataControlRowType.DataRow Then
3 Dim chk as CheckBox = CType(row.FindControl("cb_Approve"),CheckBox)
4 If chk IsNot Nothing AndAlso chk.Checked Then
5 Dim id As Integer = CInt(CType(row.FindControl("lbl_id"),Label).Text)
6 ids &= "," & id
7 End If
8 End If
9 If ids.Length > 1 Then ids = ids.Substring(1)
10 'Submit to sql with ids as param...
11 Next
I am getting an exception. Error converting '38,39' to a column of datatype int. What am I doing wrong?
I need to retrieve records where the date is in between the current date and 4 days previous.
I've tried: WHERE DateSubmitted BETWEEN GetDate() AND GetDate() - 4
it doesn't work...
Can someone help out?
It's blue in SQL Studio but I can't find it in SQL Books on-line. Iwanted to use it as a field name but don't like using [].Is it reserved?
View 6 Replies View RelatedHi guys,
Just a newbie question here.
Do we really need to use the GO keyword?
Thanks,
MeTitus
I am trying to implement a band search on my web site (concert listings) and would like it to behave a bit more intelligently than a standard match on the band name.
At the moment I have a stored procedure that just selects every show that features a band with exactly the same name as the search term. What I'm now trying to do is when the user enters a band name containing the '&' character I would also like to search using the word and 'and'. For example, if they search for 'Rise & Fall', they should get details on all shows featuring 'Rise & Fall' OR 'Rise And Fall'. Is it possible to do this within my stored procedure?
Greetings, I am a php developer, and running a little bit out of deadline in a project. Can someone provide me with a VERY simple way to implement search by keyword in C#? I have already implemented a search page (according to firstname, lastname etc) that works on a drop down menu (where you have the option to choose seach by keyword) . So, I need to change something in my SQL query to make this work. I already knew from my SQL experience that the simplest and probably the SLOWEST and MOST UN EFFICIENT one was using LIKE. I don't mind using it but I can't since I will end up having something close to that: SELECT * FROM users WHERE keyword_entered LIKE @keyword; (or '@keyword) which does not work. however SELECT * FROM users WHERE keyword_entered LIKE 'somename%'; does work! I guess the trick is in putting the % after the keyword. ( I would have done that in php by putting the entered keyword in a string and than add to it % and pass it to the SQL query and I dunno how to do that in .NET)any ideas?
View 7 Replies View RelatedHi everyone,
I have a few classes representing my data layer for my ASP.Net 2.0 Web Application. For example, UserDAL, DocumentDAL, etc... All these classes derive from BaseDAL, which stores the SqlConnection in it. The DAL classes access it through a property. The property is defined like that:
private SqlConnection connection;public SqlConnection Connection{get{ if (connection == null) connection = new SqlConnection(); if (connection.State != ConnectionState.Open) { connection.ConnectionString = ConnectionString; connection.Open(); } return connection;}}
The constructor of each DAL class is overloaded and takes a SqlConnection object. So if I need to access two DAL classes, I pass the connection of the first, to the second to prevent opening and closing the connection again and again. Here is a sample: UserDAL userDAL = new UserDAL();
userDAL.DoSomethingAndAccessConnectionProperty();
// Now userDAL.Connection is opened. Pass the connection to the constructor of DocumentDAL
DocumentDAL documentDAL = new DokumentDAL(userDAL.Connection);
documentDAL.AlsoDoSomething();
So, if I do the following:using (UserDAL userDAL = new UserDAL())
{
userDAL.DoSomethingAndAccessConnectionProperty();
DocumentDAL documentDAL = new DokumentDAL(userDAL.Connection);
documentDAL.AlsoDoSomething();
}
I assume that the connection is removed from memory, even if the DocumentDAL class has also used it. Am I right? I want to be sure that there will be no open connections.Thanks
I have a sample photo database where we have added keywords to search for photos. I wanted a way to list all of the keywords that are in the database individually. The problem is in my keyword field there are many keywords seperated by a comma.
Ex: "bull, barrel, rodeo, western, cowboy" would in the keyword field for one photo.
I wanted to select distinct all of the individual words from each keyword field in all of the records.
Can this be done? What would the query look like?
I am looking for a list like:
bull
barrel
rodeo
western
cowboy
Any suggestions?
Thanks,
Rob
If I use DISTINCT isn't there a rule where it must be the first field selected? Also, there can only be one DISTINCT field in a query, correct?
ie,
SELECT DISTINCT fieldA, fieldB
FROM tableA
but not
SELECT fieldA, DISTINCT fieldB
FROM tableA
or
SELECT DISTINCT fieldA, DISTINCT fieldB
FROM tableA
thanks again, this is a great forum
ddave
hi guys i have a query that contains several table joins
when i run the query without select distinct x,y,z,w,.. or order by docno it takes around 20 second to finish execution, when i add select distinct x,y,z,w,.. or order by docno it ruturns the same result in just 2 seconds
is adding distict keyword or order by acts as an index for the query or what ?
.
.
.
.
here is my query :
SELECT distinct p.indocno,p.CHAR_FIELD2_AR, p.CHAR_FIELD1, p.REVISION_NO, CAST(p.INDOCNO AS int) AS INDOCNO, p.CHAR_FIELD3, p.CHAR_FIELD7_AR, T.DESCRIPTION,J.DESCRIPTION AS [Section], p.SUBJECT
FROM dbo.TECHNICAL_MAIN p INNER JOIN
(SELECT MAX(revision_no) d, char_field1 c, char_field2_ar e, subcat_id j
FROM technical_main m
WHERE revision_no IN ('0', '1', '2')
GROUP BY char_field1, char_field2_ar, subcat_id) b
ON p.REVISION_NO = b.d AND p.CHAR_FIELD1 = b.c AND p.CHAR_FIELD2_AR = b.e AND p.REVISION_NO IN ('0', '1', '2')
INNER JOIN dbo.CUST_HIERARCHY_LOOKUP T ON p.CHAR_FIELD7_AR = T.ID
INNER JOIN dbo.CUST_HIERARCHY_LOOKUP J ON p.CHAR_FIELD3_AR = J.ID AND p.SUBCAT_ID = b.j
Good luck for all the folks
Hi all,
I have two datatables in my database. The first table, named Books, has two columns: BookID and Author (BookID is the primary key). The second table, named Purchases, has three columns: PurchaseID, BookID, BuyerID (Purchase ID is the primary key).
The idea here is that the Books datatable contains information regarding the book and its author while the Purchases datatable contains information on who has purchased what book.
Now, say I want to write an SQL query to extract a list of all the authors who have written a book purchased by buyer X. How would I go about doing this without having any duplicate entries? I figured that the following would work:
SELECT DISTINCT * FROM Books INNER JOIN Purchases ON Books.BookID=Purchases.BookID
But this ends up generating duplicate BookIDs if the Purchases table contains several buyers who have bought that Book. I know I could use BookID rather than * in the above query and that would work, but in reality I'm dealing with more complex tables and I would rather keep the * in there to actually get all the data out in one go.
I heard a claim recently at a SQL Server users group meeting that theTOP keyword forces sorting on a database server. I can't find anyreason this might be true and the Books Online say nothing about it.Can someone verify this claim one way or the other?
View 5 Replies View RelatedI am studying for the MSCE/MCDBA exam 70-229. In the book I am using("MCSA/MCSE/MCDBA Self-Paced Training Kit: Microsoft SQL Server 2000Database Design and Implementation Exam 70-229, Second Edition") I amlooking at the section on the ANY/ALL keyword.<QUOTE>USE PubsSELECT TitleFROM TitlesWHERE Advance > ANY(SELECT AdvanceFROM Publishers INNER JOIN TitlesON Titles.Pub_id = Publishers.Pub_idAND Pub_name = 'Algodata Infosystems')This statement finds the titles that received an advance larger thanthe minimum advance amount paid by Algodata Infosystems (which, in thiscase, is $5,000). The WHERE clause in the outer SELECT statementcontains a subquery that uses a join to retrieve advance amounts forAlgodata Infosystems. The minimum advanceamount is then used to determine which titles to retrieve from theTitles table.</QUOTE>I don't understand why this references the "minimum advance". If yourun the subquery on its own, it returns the following values:5000.00005000.00005000.00007000.00008000.0000NULL[color=blue]>From my limited understanding, the "ANY" keyword applies to at least[/color]one value, but which one? How is this determined?Any help gratefully received.Edward--The reading group's reading group:http://www.bookgroup.org.uk
View 4 Replies View RelatedI am in the process of importing an Oracle database into SQL Server.Once of the tables has a field called "EXEC".SQL Server seems to reject any queries that include that particularfield because EXEC is a keyword. For eg.SELECT ID, EXEC from USERSresults in a syntax error near keyword EXEC.I can't change the fieldname becuase it will require reworking of awhole bunch of scripts.What can I do to adjust the query?Bijoy
View 3 Replies View RelatedIs possible in SQLSERVER to use a syntax like this?select x,y from table_1 where (x,y) not in (select h,k from table_2)I've tried, but it doen't work.Do you know any workaround?Thank youFede
View 3 Replies View RelatedI've been trying to figure out the usage of "Nothing" as the scope parameter, and the more I try, the more I can confused.
It says on the RDL spec:
"For expressions inside data regions:
.......
Specifying the keyword Nothing as the scope is equivalent to specifying the
outermost data region containing the report item in which the aggregate is used."
It seems that what's it saying is that if I have an expression in a table as
= last(somefield, "the name of the table")
is the same as
= last(somefield,Nothing)
But, apparently it;s not. (I tried last, first,sum, count,CountRows, min, max...........)
it doesn't matter where I put "=last(somefield,Nothing)" in the table (i tried table header,footer, detail, and table group header, footer), none of them worked.
and I tried it everywhere in matrix, in charts.
It's just not working.
It always complains about the invalid scope not being the containing data region, containing grouping or dataset name.
However, the only way I get the "Nothing" as the scope to work is in a RunningValue function, not in any other
aggregate funcitons.
Anyone help me with this, please... I need a complete definition on the usage of Nothing as scope.
Hi,
I have a table like
ProductId, Description, Description2
where Description and Description2 are text datatypes.
I'm trying to return all records where myKeyword exists as a singular word in either of these two fields.
Should I create a child table where each word in each of these fields has its own row for each product and query against that or is there an efficient way of querying this result without creating the extra child table?
Many thanks for any pointers
Dan
I'm using an application that is generating some SQL scripts for SQL Server 2005. I'm trying tweak it so that I can run it on SQL Server 2000.
The line that I'm having trouble with is:
CREATE INDEX FKFFF41F9960601995 ON alf_access_control_entry (permission_id);(optional)
The key word "(optional)" is causing trouble.
I understand this keyword, when used in SQL Server 2005, let's the script continue and complete when errors are detected.
What is the alternative syntax to use in SQL Server 2000?
Thanks,
-Q
IS there ny substitute for this ?
=First(Fields!TouchedBy.Value, "Dataset1")
instead of keyword 'First' i need the current record , but also i need to refer dataset name also , is there any way to do that ?
Any idea?
thanks
Hello there.
I'm developing an eCommerce solutions based on the ASP.NET 2.0 Commerce Starter Kit, architechture. It uses the Provider Pattern. In my web-application, i use the CatalogProvider, to retrieve data from a SQL Server 2005 database. I call the methods through a handler class, whoch excists inside the WebApp. I also use a ShoppingCartProvider, OrdersProvider, ShippingProvider etc. in the same way.
In my Web.Config file, i have all the provers listed, and on each provider, the name of the connectionString to use are given.
My connection string looks like this:"connString" connectionString="Server=xxxx;Database=xxxx;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
The problem is, that suddently, when browsing the website, that connects to the database through the providers, i get this error:
Keyword not supported: ',server'.
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.ArgumentException: Keyword not supported: ',server'.Source Error:
Line 31: public static IDataReader GetProductsByCategory(int categoryID)
Line 32: {
Line 33: return Commerce.Providers.CatalogProvider.Instance.GetProductsByCategory(categoryID);
Line 34: }
Line 35:
Source File: d:DevelopmentASPNETSeoShopApp_CodeHandlersCatalogManager.cs Line: 33 Stack Trace:
If i then go back to my web.config file, and removes the providerName section, of the connectionString, the website works again, for a short period. When the error return, i undo the deletion of the providerName, and it will work again... For a short time...
I've also tried to use another connectionsString, like this:Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI
But then the keyword which is not supported is: ', data source'
Does anyone know what the issue might be?
Thanks in advance...
I am using the top keyword as follows in the same SP. The select and the update statements are one below the other:
Select TOP(1) col1,col2 from table1 where col3='val1'
Update TOP(1) table1 set col2= 'val2' where col3='val3'
There is a primary key on the column which is not included in either the select or the update statement.
Can anyone confirm that the both the statments will return the same row?
Hi,I have written a stored procedure to add the records to the table in DB from the report I generate, but the sored procedure gives me this error:Incorrect syntax near the keyword 'ELSE'.I am using Sql Server 2005.SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[spCRMPublisherSummaryUpdate]( @ReportDate smalldatetime, @SiteID int, @DataFeedID int, @FromCode varchar, @Sent int, @Delivered int, @TotalOpens REAL, @UniqueUserOpens REAL, @UniqueUserMessageClicks REAL, @Unsubscribes REAL, @Bounces REAL, @UniqueUserLinkClicks REAL, @TotalLinkClicks REAL, @SpamComplaints int, @Cost int)ASDECLARE @PKID INTDECLARE @TagID INTSELECT @TagID=ID FROM Tag WHERE SiteID=@SiteID AND FromCode=@FromCode SELECT @PKID=PKID FROM DimTag WHERE TagID=@TagID AND StartDate<=@ReportDate AND @ReportDate< ISNULL(EndDate,'12/31/2050')IF @PKID IS NULL BEGIN SELECT TOP 1 @PKID=PKID FROM DimTag WHERE TagID=@TagID AND SiteID=@SiteIDENDDECLARE @LastReportDate smalldatetime, @LastSent INT, @LastDelivered INT, @LastTotalOpens Real, @LastUniqueUserOpens Real, @LastUniqueUserMessageClicks Real, @LastUniqueUserLinkClicks Real, @LastTotalLinkClicks Real, @LastUnsubscribes Real, @LastBounces Real, @LastSpamComplaints INT, @LastCost INT SELECT @Sent=@Sent-Sent,@Delivered=@Delivered-Delivered,@TotalOpens=@TotalOpens-TotalOpens,@UniqueUserOpens=@UniqueUserOpens-UniqueUserOpens,@UniqueUserMessageClicks=@UniqueUserMessageClicks-UniqueUserMessageClicks,@UniqueUserLinkClicks=@UniqueUserLinkClicks-UniqueUserLinkClicks,@TotalLinkClicks=@TotalLinkClicks-TotalLinkClicks,@Unsubscribes=@Unsubscribes-Unsubscribes,@Bounces=@Bounces-Bounces,@SpamComplaints=@SpamComplaints-SpamComplaints,@Cost=@Cost-Cost FROM CrmPublisherSummary WHERE @LastReportDate < @ReportDate AND SiteID=@SiteID AND TagPKID=@PKIDUPDATE CrmPublisherSummary SET Sent=@Sent, Delivered=@Delivered, TotalOpens=@TotalOpens, UniqueUserOpens=@UniqueUserOpens, UniqueUserMessageClicks=@UniqueUserMessageClicks, UniqueUserLinkClicks=@UniqueUserLinkClicks, TotalLinkClicks=@TotalLinkClicks, Unsubscribes=@Unsubscribes, Bounces=@Bounces, SpamComplaints=@SpamComplaints, Cost=@Cost WHERE ReportDate=@ReportDate AND SiteID=@SiteID AND TagPKID=@PKIDELSE SET NOCOUNT ON INSERT INTO CrmPublisherSummary( ReportDate, SiteID, TagPKID, Sent, Delivered, TotalOpens, UniqueUserOpens, UniqueUserMessageClicks, UniqueUserLinkClicks, TotalLinkClicks, Unsubscribes, Bounces, SpamComplaints, Cost, DataFeedID, TagID) SELECT @ReportDate, @SiteID, @PKID, @Sent, @Delivered, @TotalOpens, @UniqueUserOpens, @UniqueUserMessageClicks, @UniqueUserLinkClicks, @TotalLinkClicks, @Unsubscribes, @Bounces, @SpamComplaints, @Cost, @DataFeedID, @TagIDSET NOCOUNT OFF
View 5 Replies View RelatedGetting this error.. the page runs fine but it after entering the data it produces the following..
ERROR: Incorrect syntax near the keyword 'FROM'. with the following code...Please help!
<head runat="server"><title>Parts Lookup</title></head><body style="text-align: center"><form id="form1" runat="server"><div style="text-align: center"><br /><brpan style="font-size: 10pt; font-family: Tahoma">
Enter a Part Number</span>
<asp:TextBox ID="Productnbr" runat="server" Columns="4" Width="177px"></asp:TextBox><br /><asp:Button ID="DisplayPartNumberButton" runat="server" Text="Display Price, Description, Unit of Measure" Font-Names="Tahoma" /><br />
<br />
</div><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="PartFilterDataSource" EnableViewState="False" Width="431px" CellPadding="4" ForeColor="#333333" GridLines="None" Font-Bold="False"><Columns><asp:BoundField DataField="PartNbr" HeaderText="Part Number" SortExpression="PartNbr" /><asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /><asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" /><asp:BoundField DataField="UnitOfMeasure" HeaderText="Unit of Measure" SortExpression="UnitOfMeasure" /></Columns><FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /><RowStyle BackColor="#F7F6F3" ForeColor="#333333" /><EditRowStyle BackColor="#999999" /><SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /><PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /><HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="White" ForeColor="#284775" /></asp:GridView> <asp:SqlDataSource ID="PartFilterDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ManManSQLConnectionString %>" SelectCommand="SELECT PartNbr, Description, UnitOfMeasure, Price; FROM Tbl_ODBC_PartsList; WHERE PartNbr = @Productnbr"><SelectParameters><asp:ControlParameter ControlID="Productnbr" Name="Productnbr" PropertyName="Text"/></SelectParameters></asp:SqlDataSource></form></body></html>
I am displaying advertisers on a dynamic .net page that users will
view via querystrings from a county page, then a city page , as they
can pick a zone , then view the advertiser's ad predicated on the
zone they pick. I want to have advertisers on a premium plan that can
be viewed in all areas of the city, regardless what zone the user
picks. Trying the below does not suffice my resultset (the queriedzone
is a variable as the request.querystring for the zone ; 'all' is the
indicator for an advertiser who should be seen in all zones)
sqlstr = "select company, address, email from advertisers where zone IN ('" + queriedzone + "','all') "
??? thanks in advance ed
HiI am getting the following error on my Select statement: Incorrect syntax near the keyword 'AS'. SELECT [A], [B], [C], [D], [E], [F], [G], [H], [I], [J], [K], RowFROM(SELECT ROW_NUMBER() OVER (ORDER BY [J] DESC)AS Row, [A], [B], [C], [D], [E], [F], [G], [H], [I], [J], [K]FROM [TABLE]WHERE (([A] LIKE '%' + @A+ '%') OR ([K] LIKE '%' + @K+ '%')) AS LogWithRowNumbersWHERE (Row >=91 AND Row <= 100) I used the following select statement as a template (which works fine): SELECT [A], [B],
[C], [D], [E], [F],
[G], [H], [I], [J],
[K], [L], Row
FROM (SELECT ROW_NUMBER() OVER (ORDER
BY [H] DESC)
AS Row, [A], [B],
[C], [D], [E], [F],
[G], [H], [I], [J],
[K], [L] FROM [TABLE]
WHERE (([J] = @J) AND
([E] >= @E)) AND
(([K] < [L]) OR (([K] = 0) AND
([L] = 0)))) AS LogWithRowNumbers
WHERE (Row >= 82 AND Row <= 90) What is the difference that would make one work and the other not work?Thanks if you can help,Jon
Hi,I was just wondering if some kind soul on here could help me. I created a table in a database with called 'EuropeBroadcastList', with the following columns: Name, First Name, First, Last Name, Last, Title, Company, Photo.I have created a query whereby I want to create a new table with only specific columns called 'EuropeBroadcastSorted' and sort the names in 'EuropeBroadcastList' by the 'Last' column. The query is: CREATE TABLE europebroadcastsorted AS (SELECT [name], title, company, photo, [Last] FROM EuropeBroadcastList ORDER BY Last ASC); When I execute it I get the following syntax errors: Msg 156, Level 15, State 1, Line 2Incorrect syntax near the keyword 'AS'.Msg 156, Level 15, State 1, Line 4Incorrect syntax near the keyword 'ORDER'.Can any kind person help me resolve this?Thanks Rob
View 4 Replies View Relatedhi,i am trying to connect sql server 2005 from my asp.net applicationi have create DSN for this ..then i am getting the following errorKeyword not supported: 'dsn'. in sql serverplease provide me the solution
View 5 Replies View RelatedCan someone help me? I am trying to script an SQL statement that would allow someone to INSERT a new username into a database where it is not a duplicate entry. The table is like this:
UserID - int, 4, identity(1,1)
UserName - nvarchar(50)
UserPass - nvarchar(50)
The code to execute this where i am getting the errors is this:
Function ChooseUName()
If Page.IsValid Then
Dim objCon As New SqlConnection(con)
Dim sqlInsert As String = "INSERT INTO tblUser (UserName) " & _
"VALUES (@Username) WHERE NOT EXISTS (SELECT UserName FROM tblUser)"
Dim cmd As New SqlCommand(sqlInsert, objCon)
cmd.Parameters.Add("@Username", SqlDbType.NVarChar, 50)
cmd.Parameters("@Username").Value = txtUsername.Text
Dim id As Integer
Try
objCon.Open()
id = cmd.ExecuteScalar()
Finally
If objCon.State = ConnectionState.Open Then
objCon.Close()
End If
End Try
Response.Write("Your User ID is: " & id.ToString())
Response.End()
End If
End Function
This is the error:
Incorrect syntax near the keyword 'WHERE'.
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: Incorrect syntax near the keyword 'WHERE'.
Source Error:
Line 73: Try
Line 74: objCon.Open()
Line 75: id = cmd.ExecuteScalar()
Line 76: Finally
Line 77: If objCon.State = ConnectionState.Open Then
PLEASE HELP!! I'M ON A STRICT DEADLINE!!! :o THANKS IN ADVANCE!
y am i having keywork not supported? is there anything wrong with my connection string ??
==========web config================
<appSettings>
<add key="db" value="icms" />
<add key="db_user" value="sqladmin" />
<add key="db_server" value="server" />
<add key="db_pwd" value="12345" />
<add key="session_timeout" value="600" />
</appSettings>
==========DB.vb==============
Dim myDB As New SqlConnection
Dim myCMD As New SqlCommand
Public Sub New()
Dim db_server = AppSettings("db_server")
Dim db = AppSettings("db")
Dim db_user = AppSettings("db_user")
Dim db_pwd = AppSettings("db_pwd")
Dim DBConnection As String = "DRIVER={SQL Server};" & _
"SERVER=" & db_server & ";" & _
"DATABASE=" & db & ";" & _
"UID=" & db_user & ";" & _
"PWD=" & db_pwd & ";" & _
"OPTION=3;"
myDB.ConnectionString = DBConnection
myCMD.Connection = myDB
End Sub
=============================
Hi Guys,
This one is driving me nuts... I have been getting this error in my Asp.Net page. I run the profiler and then I can grab the actual query, and when I run this query in query analizer, it works just fine...
I have no clue at all about what's going wrong with my code or query...
cmd.CommandText = "exec mydatabase.dbo.mytable @select = 'Select convert(varchar(20),J.Datecreated,107)as Date, max(J.datecreated)As DateOrd from table1 J Left Join table2 C on J.CustID = C.CustID where C.Mode = 1 group by convert(varchar(20),J.DateCreated ,107) order by max(J.datecreated) DESC', @sumfunc = 'count(ID)', @pivot = 'Staff', @table = 'table1'"
-=========================
STORED Procedure
CREATE PROC myTable
(
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)
)
AS
DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
EXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')
SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )
SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'
SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivot
DROP TABLE ##pivot
SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')
print @select
EXEC (@select)
SET ANSI_WARNINGS ON
SET NOCOUNT OFF
thanks in advance...
I’m working on a project that will allow a user to search through approx 100,000 records in a SQL table. Three of the columns are ‘text’ fields that hold paragraphs of text. The user interface has a ‘general search’ option so that they can enter a number of key words and the database will return a count of the records found containing the keywords.
At the moment I split the input and then build a query based on their input. For instance if they enter ‘hello world’ the input is split into two strings ‘hello’ and ‘world’. I then build the query in a loop and get a query like so:
Select Count(ID) as myCount FROM myTable WHERE (colOne like ‘%hello%’ AND colOne like ‘%world%’) OR (colTwo like ‘%hello%’ AND colTwo like ‘%world%’) OR (colThree like ‘%hello%’ AND colThree like ‘%world%’)
Unfortunately this query runs EXTREMELY slowly and just seems wrong. Is there a more efficient way I should be doing these types of searching? This method works ok on 100 records, but this is the first time I have worked on such a large database.
Is it also possible to search a text column and look for exact matches?
For instance I have 2 records with their textfield containing:
Rec 1: the news for today is blah blah. Rec 1: this is a new item
If I currently search for ‘new’ (select colID from myTable where colOne like ‘%new%’) I will get both these records, but I’d really only like to pull out the second record.
Any help would be great appreciated! :)