I've uploaded a new version of my article on Dynamic Search Conditions
on http://www.sommarskog.se/dyn-search.html. I've revised the article to
cover SQL 2005, and made a general overhaul of the content. There was a
*very* embarrassing error that I've corrected.
I've also added a new interesting method for static SQL. I've found that if
you say:
SELECT ...
FROM tbl
WHERE (key1 = @key1 AND @key1 IS NOT NULL)
OR (key2 = @key2 AND @key2 IS NOT NULL)
OR (key3 = @key3 AND @key3 IS NOT NULL)
This will use indexes if all columns are indexed, and furthermore SQL
Server will decide at run-time which index(es) to access. The article
includes a trick where you can combine this with the normal conditions for
dynamic searches for very good performance under some circumstances.
I also cover the new OPTION (RECOMPILE) to force statement recompile.
I was hoping that it could lead to just as good query plans as dynamic
SQL, but it's far cry from that.
--
Erland Sommarskog, SQL Server MVP, Join Bytes!
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
I have a simple gridview control set up that contains a single ControlParameter (a DropDownList) whose value is used in my SqlDataSource's SelectCommand: SelectCommand="SELECT * FROM [Wood_table] WHERE [wood_type] = ISNULL(@wood_type, [wood_type])" The ISNULL check is so that I can select "ALL" from my dropdown and get all the rows with null values. Everything works fine. Now what I'd like to do is exclude a specific wood_type value from the query if a checkbox control is selected. So what I'd like my select query to be when it's checked is something like SelectCommand="SELECT * FROM [Wood_table] WHERE [wood_type] = ISNULL(@wood_type, [wood_type]) AND @wood_type <> 'pine' " So I'd like the option of excluding that certain type of wood from the default query (all rows). I thought it might be better to just have a value in the dropdown list that was "ALL except pine" but that doesn't seem like it would work, what would I bind that to? I fooled around with having the CheckBox oncheckchanged event set a global based on the checked status, easy enough, but then how can I modify my SelectCommand? Should I just access the SqlDataSource object programmatically in my CheckBox handler and fiddle with the SelectCommand property? I tried this and it works, but this seems messy, now if I modify my GridView in Design mode I need to remember to update my SelectCommand strings in the CheckBox handler too. Is this the best way to do this?
My question is fairly simple. When I join between two tables, I always use the ON syntax. For example:
SELECT
* FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId)
No problems there. However, if I then decide to further filter the selection based on some trait of the UserRole, I have two options: I can add the condition as a WHERE statement, or I can add the condition within the ON block.
--Version 1:
SELECT
* FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId) WHERE
UserRoles.Active = 'TRUE'
-- Version 2
SELECT
* FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId
AND UserRoles.Active = 'TRUE')
So, the question is, which is faster/better, if either? The Query Analyzer shows the two queries have the exact same execution plan, which makes sense, since they're both joining the same tables. However, I'm wondering if adding the condition in the ON statement results in fewer rows the JOIN statement initially needs to join up, thus reducing the overall initial size of the results table before the WHERE conditions are applied.
So is there a difference, performance wise? I imagine that if Users had a thousand records, and UserRoles had 10 records, then the JOIN would create a cartesian product of the two tables, resulting in 10,000 records in the table before the WHERE conditions are applied. However, if only three of the UserRoles is set to Active, would that mean that the resulting table, before applying WHERE conditions, would only contain 3000 records?
Please help, I am trying to write a dynamic search stored procedure using three fields. I use the same logic on the front end using VB to SQL server which works fine, but never tried a stored procedure with the logic. Can you please help me, construct a stored procedure. User can choose any of the three(progno, projno, contractno) fields as a where condition.
I ma using asp.net as front end with sql server backend.
CREATE PROCEDURE dbo.USP_Searchrecords (@ProgNO nvarchar(50), @ProjNOnvarchar(50) , @ContractNOnvarchar(50)) AS DECLARE @myselect nvarchar(2000) DECLARE @psql nvarchar(2000) DECLARE @strsql nvarchar(2000) SET NOCOUNT ON
@psql = "SELECT * FROM Mytable"
IF @ProgNO <> '' then strsql = WHERE ProgNO = @ProgNO end if
If @ProjNO <> '' then if strsql <> '' then strsql = strsql & " and ProjNO =@ProjNO ELSE strsql = wHERE ProjNO =@ProjNO END IF END IF
If @ContractNO <> '' then if strsql <> '' then strsql = strsql & " and ContractNO =@ContractNO ELSE strsql = wHERE ContractNO =@ContractNO END IF END IF
I have a table named "Persons" which has the following columns [ Name ,Age, City]. I have a Windows app which has 3 textboxes for each column. My requirement is when I enter only name and enter the search button, I need result similar to this query.
select * from persons where name like '@tbname%' when I enter only age and enter the search button, I need result similar to this query. select * from persons where age =@tbage when I enter name and city, I need result similar to this query. select * from persons where name like '@tbname%' and city like '@tbcity%'
If I don't enter any fields and enter the serach button, I need result similar to this query.
select * from persons for these 3 fields I might give any combination as above. But how can I have a single query with all these combinations. I want a single query capable of doing this. I cannot have query like this, select * from persons where name like 'tbname%' and city like 'tbcity%' and age =@age
Because if I give only name, city is considered as null nad age is considered as 0 and I get empty result. I cannot have Stored proc and I cannot do much in C# like using "selectqueryBuilder" etc. I need pure SQL query.
MS has post a KB article on how to post a question on a online forum...
http://support.microsoft.com/kb/q555375
At first I though this was hilarious, but there is actually some good information in here that is applicable on this forum as well as anywhere else. Perhaps Brett could add this as a sticky?
Dear All, i'm in the transactional replication environment. we need to add one new table to the publisher. it is sql server 2005 environment. please explain me the steps
and in another table, i need to change the data type of a table.
please guide me
Arnav Even you learn 1%, Learn it with 100% confidence.
If I want to unpublish an article thru Enterprise Manager, it does not allow me to uncheck it at publication properties. It only allows me to uncheck articles if I delete the subscription first. Does anybody know how tp do this in Enterprise Manager without deleting the subscription?
So i execute sp_dropsubscription and sp_droparticle for the table for all publication to that article in the database.
Usually i just alter the table and then execute sp_adddarticle and sp_addsubscription afterwards and everything is cool.
However in this case after i drop the subscriptions for the article, when i try alter the table it says it is being replicated.
I query sysobjects and see that the table has replinfo = 1 , this is snapshot replication, but i only have transactional replication ? I used to have snapshot but that was dropped long ago.
I then query sysarticles and i find the table, however the pubid (publication id) for the table is equal to the publication id of another databases publication ??? I also have found in sysarticles articles with a publication id's equal to publications that do not exist, for example articles will have pubid of 2 , but if i run sp_helppublication on all user databases there is no publciation with an id of 2 ?
Please help, even after i drop all subscriptions to an article it seems that sql server thinks the article belongs to another databases publciation or publications that no longer exist?
Maybe there is some sort of cleanup sp i can run or something but it seems to me sql server has gotten articles confused with old deleted publications that no longer exist.
Therefore after dropping all subscriptions i still cannot alter tables as sql server think it is still being published but it is not!
i need to filter an article based on a user-supplied datetime filter (the datetime parameter is specified by the subscriber just before replication). at the same time i need to filter again by user (different subscribers get different rows).
i already did the user-based filter using HOST_NAME( ). but the difficulty here (al least i think so) lies in passing 2 parameters to the filter. i cannot rely on using SUSER_SNAME to pass the user filter, because no one will want to create 500 user accounts. so i guess the only solution here is to pass both parameters using only HOST_NAME( ) and then write 2 splitting functions which uses HOST_NAME( ) as its parameter. am i right ?
publisher/distributor is sql server 2005, all subscribers use sql mobile.
I'm setting up Transaction Replication b/w SQL Server 2K and SQL Server 2K5. I have published Tables, Views and SPs as articles. When I try to modify the published Stored procedure, the changes are not replicated.
When I Reinitialize the Subscription and start the Snapshot agent, it is copying the changes
made. But all articles are reinitialized again, So it takes huge time to do this.
Is there any way to just reinitialize only the changed article? Or Is there any work around for this problem?
The chapter from my book that talks about upgrading packages from DTS to SSIS has been posted here : http://www.quepublishing.com/articles/article.asp?p=605035&rl=1
Didn't even know it until I happened to be doing a search on upgrading and the article popped up in the search...
the msdn article explains how to input new data to a databse and return the primary key of the inputted row. It works perfectly. However, it explains how to insert a value, but there is a problem. It seems to set the value to be submitted in the VB code, instead of having the value be the user's input in the textbox. Look for the following line in the code below: newRow("ClientFileNumber") = "ClientFileNumber" It inputs "clientfilenumber" instead of what is actually inputted in the texbox. Does anyone know how to bypass this, to not have the words "clientfilenumber" inputted?Dim sqlconn As SqlConnection = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Client.mdf;Integrated Security=True;User Instance=True") Dim catDA As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Orders", sqlconn) catDA.InsertCommand = New SqlCommand("JobInsert", sqlconn) catDA.InsertCommand.CommandType = CommandType.StoredProcedure catDA.InsertCommand.Parameters.Add("@ClientFileNumber", SqlDbType.VarChar, 50, "ClientFileNumber")Dim NewJobNumber As SqlParameter = catDA.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "OrdersID") NewJobNumber.Direction = ParameterDirection.Output
sqlconn.Open() Dim catDS As DataSet = New DataSetcatDA.Fill(catDS, "Orders")
Dim newRow As DataRow = catDS.Tables("Orders").NewRow() newRow("ClientFileNumber") = ""catDS.Tables("Orders").Rows.Add(newRow) catDA.Update(catDS, "Orders")
Hi, I'm building a straightforward-ish news site. Currently, the story details (e.g. headline, description, author, date) are stored in a SQL DB. The news is categorised and the category details are also stored in an SQL table. However - what is the best way to store the actual news article? At the moment, when the user enters a story, they input the details and article text. The details are saved in the DB and the text is saved as an XML file with filename corresponding to the article DB primary key. When the story is "read" the app pulls the details from the DB and loads up the appropriate XML file from disk. For various reasons, I need to keep the article stored as XML, either in a file or in the DB. The DB provides for faster sorting and retrieval, and I don't want to store large amounts of data (i.e. the article itself) in the DB if avoidable. I guess there are a few ways to do it - 1. Store details in DB and article as XML file.2. Store details and article in same DB table3. Store details in one DB table and articles in another I would imagine that 3 would be the best, but would there be a performance hit? What is the maximum size of field (i.e. article size) I can have in a table? Cheers Graham Wilson.
We're replicating columns in a table from 7.0 server to SQL2k server. Once we've got the data on SQL2k, we were able to take advantage of DTS that was not available in version 7.0.
I recenlty added a column to the article and changed the DTS accordingly (transformation columns). However, I'm getting this error ever though I added the new column in the DTS.
------- The number of columns in the bcp file does not match what is defined in the DTS package. Regenerate the package.
-----
I've recreated the package with no luck. This is becoming urgent as it's supposed to go into production soon.
I am having a server where replication is set up between 2 differnt databases. It is currently running. I want to add a couple of tables to the replication. I tried using sp_addArticle, but after executing it, in the properties of the publication it shows the new tables, but at the database level the tables are missing.
I tried with sp_addsubscription but I am getting strange error:
Server: Msg 14100, Level 16, State 1, Procedure sp_addsubscription, Line 240 Specify all articles when subscribing to a publication using concurrent snapshot processing.
What can I do to publish the tables into the target database?
I am running merge replication (SQL 2000 with SP2) with an anonymous pull subscription. The application vendor has come out with update that requires adding a table to a database. The vendor has created scripts that will add the table, as well as some stored procedures. If I apply the scripts to both servers and add the table as a new article to the publication, am I going to have to apply a snapshot of the entire database (which is very large)?