Is it possible to use wildcards with an equals statement? Such as
SELECT * FROM Table WHERE City = '%' AND State='Ca'
Bascially just stating where city equals anything...
I know you can do it with a LIKE statement such as...
SELECT * FROM Table WHERE City LIKE '%' AND State='Ca'
but is that very efficient?
The reason I want to do this is because I want to programmitcally
set the city, so just ommiting it won't work
Also, using City LIKE '%' seems to not include NULL...is there anyway
to include NULL as well as anything else?
SELECT Loan.loan_No AS Loan_No, Loan.customer_No AS Customer_No, Customer.first_name AS First_name, Customer.second_name AS Second_name, Customer.surname AS Surname, Customer.initials AS Initials, Bank.Bank_name AS Bank_name, Branch.Branch_name AS Branch_name, Branch.branch_code AS Branch_code , Bank_detail.bank_acc_type AS Bank_acc_type, Transaction_Record.transaction_Amount AS Transaction_Amount, Transaction_Record.transaction_Date AS Transaction_Date, Loan.product AS Product, Product.product_Type AS Product_Type, Product_Type.loan_Type AS Loan_Type
FROM Transaction_Record INNER JOIN Loan ON Transaction_Record.loan_No = Loan.loan_No INNER JOIN Product ON Loan.product = Product.product INNER JOIN Customer ON Loan.customer_No = Customer.customer_no INNER JOIN Bank_detail ON Customer.customer_no = Bank_detail.customer_no INNER JOIN Branch ON Bank_detail.Branch = Branch.Branch INNER JOIN Bank ON Branch.Bank = Bank.Bank INNER JOIN Product_Type ON Product.product_Type = Product_Type.product_Type
SELECT CASE WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END AS Population_Range, COUNT(CASE WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END) AS [No. Of Countries] FROM Country GROUP BY CASE WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END
I'm required to allow users to order items in a field to be displayed on a page in the order they specified.
For example: A user can drag and drop items in a list to specify the order it will be displayed in.
I have my drag and drop code ready to do this. I have an idea on how to do this but I think it’s too inefficient. I was going to create an orderby field and populate it with a number that corresponds to the position of the item. However, as one can deduce, if a user drags and drops a record between two others, I would have to change not only its orderby number but then change all the other items orderby number.
For instances if I dropped an item with an orderby number of 3 between 6 and 7 I would have to change the 3 to a 7 and then recursively change all the other records orderby numbers up to 3 and then change everything after 7.
Well, I hope I make sense. It’s easier to visualize it on paper.
Does anyone know how to tackle this issue of user dynamic ordering?
My main table has the following structure:t1 (id_primary, id_secundary, name) i.e. [(1,1,"name1"), (2,1,"name2")]I want to join this table with the following second table:t2 (id_primary, id_secundary, value) i.e. [(1, NULL, "value1"),(NULL,1,"value2")]The join should first try to find a match on id_primary and only if thatfails it should find a match on id_secundary. Every row in t1 is matchedagainst a single row in t2.The following query works:selecta.name, isnull(b.value, c.value)fromt1 a left outer join t2 b on a.id_primary = b.id_primaryleft outer join t2 c on a.id_secundary = c.id_secundaryI'm wondering though if it would be possible to write a query that only usest2 once, since it actualy is quite a complex query that is calculated twicenow. Any ideas (besides using a temp table)?
hi,In MySql,we can run below query select appid,dvbpath,business from ocgxmldbinfo group by appid but in MSSql,it can't!so i want to know whether the following query equals it? select distinct appid,dvbpath,business from ocgxmldbinfo order by appid
I have a table called "Inc_Exp_Accounts". The table has ledger account numbers and names. It also has a third column called "IsExpense". The IsExpense column is a bit field = 0 (false) if the account is an income account and = -1 (true) if the account is an expense account. I only have income and expense accounts. I do not have other accounts such as asset accounts. The distinguishing thing about income accounts is that the account number (an nvarchar(11) type) is a '3'. Anything else makes it an expense account.
I would think I can use the following SQL statement to correctly set the IsExpense column:
UPDATE Inc_Exp_Accounts SET IsExpense = IIF(LEFT(Account_Number, 1) = '3', False, True) But nooo, I cannot! I cannot even run it because Visual Studio SQL Syntax checker rejects it. It complains about the second '='. If I change the second '=' to '>', then it complains about '>'. Therefore, I think I have the particular character about which it complains.
Ths specific complaint (error message) is: "Error in list of function arguments: '=' not recognized. Unable to parse query text.". So what is wrong?
I have an ASP.NET web application that uses a Treeview control to display what can potentially be a very large data set. In the past, I would just run a recursive stored procedure in my database that would output the XML which I would save to a file. The Treeview used the XML file as its data source. I did this because it can take so long for the stored procedure to run (10 seconds or more) that, it isn't practical to have the treeview point directly to the stored procedure. This worked well enough because the data didn't change very often.
Now, it looks as if the application will be used in a production environment, and I really need to find a way to supply up-to-date data to the treeview in a dynamic way. I have tried creating a view that would provide XML and that would be updated any time the target table is updated but, that has not worked. I have also tried creating a trigger that would output to an XML file any time an edit was made (using the xp_cmdshell functionality) but, that has proven difficult as well.
Is there a simpler solution that I am just missing? I just want an up-to-date XML representation of the data that is a result of a recursive function.
We have a website that accesses our SQL databases. In the past, we used our internal employees to improve our SQL databases. However, we want to outsource the work.
There is a lot of information we would like to keep private from the outsourcing.
Is there a way to efficiently make test data throughout our database without changing our original database? Is a way to easily update our database to the new changes?
I found this product through Google EMS Data Generator for SQL Server http://www.sqlmanager.net/en/products/mssql/datagenerator Would this program help us make test data?
Hello, I perform queries on tables with 500,000 plus records, when I use the like clause or the = for record names with large numbers I get different counts with each run. As an example if I was searching retail stores and k-mart was one I get counts like the following 1st run: k-mart 2200 2nd run: k-mart 2240 3rd run: k-mart 2197 etc. etc. The records may be k-mart inc or kmart inc or k-mart etc. If anyone has a better understanding of how the items are searched for and knows a better way please respond. Thank you in advance.
Hi,I'd be interested in people's thoughts about the following. A user on my site will be searching for a venue name, and that could officially include a sponsor which the user might not search for. Now I am using the AutoCompleteDropdown from the AJAX Control Toolkit, so the user will start typing in a few characters and the results will be returned. I can generate the results from sql by doing a simple LIKE '%' + @searchTerm + '%' however, this fills me with great fear of table scans. At the moment, we'd be querying against a table of 5K records, but our application is very new.I'm thinking one option is to split the words into another table - a one to many relationship to hold each word of the venue. The benefit of this would be that you could do a:LIKE @term + '%'but then I have the cost of the join. (And the added complexity which is not a major issue)Any thoughts/tips?Thanks!
We have a SQL Server 2012 Enterprise live transactional database that is now growing over 1G per month and is becoming a size problem for us. It is currently at 23G. Character type fields are all Unicode and I have calculated a savings of 5G in space converting only 2 such fields averaging 206 characters each to non-Unicode, and almost 10G in space if we convert a few more of them from nchar and nvarchar to char and varchar types. These fields will never have a requirement to hold Unicode characters that cannot be in the SQL_Latin1_General_CP1_CI_AS collation as they come in as plain ASCII originally and will always do so per the protocol standard.
I’m the software architect and chief C# developer though only a DBA hack or I would not have designed our database to have Unicode fields for high volume tables that did not need Unicode for those fields when the database was created 3 years ago. I want to correct this mistake now before we finalize converting to an AlwaysOn environment to support with various performance and backup issues.
After downsizing these two or more fields, we would like to shrink the database one time to take advantage of the space savings for full backups, and for seeding an AlwaysOn environment.
1.What is the safest and most efficient conversion technique for downsizing columns from nchar/nvarchar to char/varchar types? Esp. when there are multiple fields in the same table to be converted. I tested doing an “add new column, set new=old, drop old, rename old to new” for both of the main two fields I want to convert from nvarchar(max) to varchar(max), and it took 81 minutes on our test server (4 virtual core, 8G memory) before running out of disk space even though there was 8G left on the disk, and the db has unlimited size set (Could not allocate space for object 'dbo.abc'.'PK_xyz' in database 'xxx' because the 'PRIMARY' filegroup is full). I did delete an old database before it finished after getting a disk warning so maybe it did not count that new space. Regardless it was too slow. And this was on just the two largest of these columns (12.6M rows) and only ran 2 to 3% CPU busy so seemed not very efficient, and indicated unacceptable downtime if we were to convert even these two fields much less any additional fields. Average field size for these two fields was only 206 characters or 412 bytes each. Another technique I plan to try is to create the new table def in a new schema, select into it from the old table, then move tables amongst schema and delete the old table. I have a FK and indexes to contend with on the table.
2.If I figure out how to do #1 efficiently within an acceptable maint window, what is the safest practice for doing a one-time shrink and end up with organized/rebuilt indexes and updated Statistics? I understand the logic of not doing regular shrinks and that sometimes it can actually increase the size.
3.Is there any third party tool that could take a backup and restore it into a new database with the modified field definitions or otherwise convert certain field types?
Situation: SQL Server 2000. At my new employer they have a production database on one server and a copy of it that is set to read only on another server which is used for reporting.
#1 They have an SQL Server Agent job on the production server that: (2 times a day)
Backs up the production database Copies the backup file to a directory on the reporting server. (Its pretty big and can take time if there are problems with the LAN)
#2 They have an SQL Server Agent job on the Reporting server that: (scheduled to run 2 hours or so after the job on server 1 has runthey figured that it would be a safe bet that the backup and copy process of the first job would be done by then)
Breaks the user connections to the reporting database Performs a restore on the reporting database using the backup file that was copied to the holding directory by the production job. Sets some permissions for various users. Sets the reporting database to READ ONLY. What I would like to do is find a more efficient way to create this reporting database, I have started doing research into DTS methods but would like some opinions from more experienced users.
This seems to be a rather old problem (http://www.themssforum.com/SQLServer/Does-empty/) but I couldn't find an answer yet.
The problem is: I have two tables t1 and t2 where t1 is a staging area of t2. t1: (id int not null, phone varchar(30)) t2: (id int not null, phone varchar(30))
Data in t1: (1, '') <- empty string Data in t2: (1, ' ') <- a blank
Comparing t1.phone with t2.phone results in equality which in my opinion isn't correct.
The question ist: How can I change the behaviour of SQL-Server to result in inequality so that the change in my staging table is detected correctly?
Hello,I currently have Table1 and View1.View1 is a query from 2 or 3 tables that works fine on its own.However in my current query if I try to use it...something like...SELECT a.col1, a.col2, a.col3, b.col1, b.col2, b.col3FROM View1 a JOIN Table1 b on a.col1 = b.col1WHERE a.col2 <b.col2 OR a.col3 <b.col3It throws an error "Server: Msg 446, Level 16, State 9, Line 1 Cannotresolve collation conflict for not equal to operation."Clearly I need to use collation between Table1 and View1, But I dontknow where I need to use "COLLATE SQL_Latin1_General_CP850_CI_AI" andhow? this is the collation set on Table1.Thank you!Yas
HelloI am trying to search 2 columns on a databsae table using a string put into a box, the code i have at the moment is SqlConnection conn = new SqlConnection(SqlDSFindPost.ConnectionString); SqlCommand cmd = new SqlCommand ("SELECT * FROM tblBlog WHERE UserName LIKE @UserName OR Title LIKE @Title; ", conn); cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 50).Value = '%' + TextBox1.Text + '%'; cmd.Parameters.Add("@Title",SqlDbType.NVarChar, 50).Value = '%' + TextBox1.Text + '%'; conn.Open(); cmd.ExecuteNonQuery(); GridView1.DataBind(); I have tried all sorts of strings and even typeed the string directly into the parameter but never get any results, yet when i type the wildcards directly into the textbox i get the correct rows returned. Can anybody see anything wrong with my code and tell me where i am going wrong, or alternativly point me in the direction of some c# code for searching a database similar to the search box abovei dont do a lot in asp or c# so this is driving me crazy Thanks for looking
I have a need to use wildcards in a sql statement. e.g. select * from tbl where field='%computer%'. How can I substitute the string "computer" for a variable declared in the stored procedure. Procedure Sample @Str varchar(50) AS select * from tbl where field = '%' & @Str & '%' (How do incorporate the wildcard variable @Str?
I want to replace the NNNYYYYMMDDHHMM with a wildcard (for example *), so that import will pull ANY .SDF files in, but it will not run. i get the following:
output ------------------------------------------------------------------------------ DB-LIBRARY error: Bcp: Unable to open host data-file.
I need to replace the use of wild cards in my query with something else which achieves the same thing. The problem is the web application which uses the query does throws an error when using '%' characters. Any ideas?
The following statement appears in the where clause:
AccType.Value like '@Opened_By[%DIST%APP% as Distance and Business Provider, DIST% as Distance, APP% as Business Provider]'
I’m trying to use case statement in my view with wildcards for '%Tradies%', instead of listing all items
WHEN 'Tradies Rebate1' THEN 'Test' WHEN 'Tradies Rebate2' THEN 'Test' WHEN 'Tradies Rebate3' THEN 'Test' WHEN 'Tradies Rebate4' THEN 'Test'
At this moment '%Tradies%' does not work and gives me null values in EventGroup column.
Here’s my statemnt ------------------------------------------ CASE [dbo].[Event].[EventName] --WHEN 'Tradies Rebate1' THEN 'Test' --WHEN 'Tradies Rebate2' THEN 'Test' --WHEN 'Tradies Rebate3' THEN 'Test' --WHEN 'Tradies Rebate4' THEN 'Test' WHEN '%Tradies%' THEN 'Test' WHEN 'Install Products' THEN 'All Installed' WHEN 'Installation Product Conversion' THEN 'All Installed' WHEN 'Installation Products' THEN 'All Installed' WHEN 'BK 3' THEN 'All Bright Kids' END AS [EventGroup], ------------------------------------------
I have a SQL statement which is generated dynamically. I need to know what is the correct syntax for this
WHERE status = 'open' AND salesman = * AND dat = * AND customername = *
i.e. fetch everything WHERE status = 'open'
I know that simply WHERE status = 'open' would do the trick but I need it like the first example because of the way the statement is being generated i.e. this salesmen bit is like this.
If Salesman <> "*" Then sql2 &= " AND salesman = '" & Salesman & "'" Else sql2 &= " AND salesman = *" End If
Hi I'm using the full-text indexing on a table and I'm trying to implement a search where users can search for words and use wildcards themselves. However I'm working on a method so that can enter a wildcard in the middle of a word to get records where they are unsure of the spelling etc. For instance, a search of 'Ste*en' should return results like 'Steven' and 'Stephen' etc. So if they are searching for word 'establishment' they can search for 'estab*ment' and it should return all the records using this query: SELECT * FROM myTable WHERE CONTAINS(myField,'"estab*ment"') If I do a wildcard at the end e.g: SELECT * FROM myTable WHERE CONTAINS(myField,'"estab*"') I get the results I am looking for. But the middle wildcard does not seem to work as expected even though it is the syntax used on MSDN and other SQL info sites. Is there something I am not doing properly?
I have a stored procdure in SQL Sever that accepts paramteres. I am trying to return rows where parameter that is passed is somewhere in the cuustomer's name. Without the variable the SQL would look like this:
SELECT * FROM tbl WHERE CustomerName LIKE '%Smith%'
I can't figure out how to replace LIKE '%Smith%' with a varible. I tried '%@CustomerName%', ('%' + @CustomerName + '%') and neither works. Any ideas? Thanks
ps my column's type is char(50) and so is the variable so trailing spaces don't matter.
Hi all,I am creating an ASP.NET site, and I'm having lots of issues trying to get wildcards to work with the following query:DECLARE @Status varcharDECLARE @AssignedTo intDECLARE @AppID intSELECT dbo.Issue.IssueID, dbo.Issue.ReportedBy, dbo.Issue.ShortDescription, dbo.Issue.DateReported, dbo.Issue.Status, dbo.Priority.Description AS Priority, dbo.Application.ApplicationFROM dbo.Issue INNER JOIN dbo.Priority ON dbo.Issue.Priority = dbo.Priority.PriorityCode INNER JOIN dbo.Application ON dbo.Issue.Application = dbo.Application.ApplicationIDWHERE (dbo.Issue.Status LIKE '%' + @Status) AND (dbo.Issue.AssignedTo = @AssignedTo) AND (dbo.Application.ApplicationID LIKE '%' + @AppID)ORDER BY dbo.Priority.PriorityCode When running this through query analyser I get the error:Server: Msg 245, Level 16, State 1, Line 5Syntax error converting the varchar value '%' to a column of data type int. Could someone help me understand this please?Thanks