Generating A Datatable From Results Of A Dynamic Query?
Aug 25, 2004
I am developing a datagrid which will display a summary "report" of sales revenue grouped by a particular field. There will also be a drill-down on this field that will display in more detail the table of data that was used for the summary.
Because the user is selecting multiple criteria under which to run the search, I have created a dynamic query that gathers all the necessary data I need for both the drill down and the summary based on the variable parameters of the user. I've optimized the query that gathers the detailed data (taken from 7 tables) to execute far under a second.
So, that said, here's my question: It seems the most efficient way to get the summary data is to run it against the datatable (which gathers the detailed data) created by the dynamic query and just pass them both into a dataset. Can this be done? Originally, I was calling 2 separate sprocs in my application - one for the detailed data and another for the summary data using a "group by" on the table that was produced by the dynamic query (using "INTO TABLE" in the SELECT statement of the dynamic query). With this method, I received an access exception by asp.net. for the table created by the dynamic query so have dropped the "INTO TABLE", not to mention it increased the performance considerably NOT using the table.
Any suggestion on the most efficient/optimal method to use the data generated from the dynamic query sproc for the summary data? I am trying desparately to avoid running the dynamic query again just for the summary data.
I am a total newbie, so would appreciate any feedback. Also, would someone please tell me the datetime stamp function to print so that I can see how many milliseconds it takes to execute stored procedures?
Hello, I have a query that works in query analyzer; it looks that a certain date is between the start and end date of a certain value. I also have a status field, which can be null, but if provided, provides the appropriate status to filter by. Again, the query works in QA, but not in the application. I test in SQL by using start date = '1/1/1900', end date = '12/31/9999', and status = null. Results are returned. But, not when the results are done through code. In code, I set the begin date to new DateTime(1900, 1, 1), the end date to DateTime.MaxValue, and the status to a null string. But, no results are returning. Why isn't that mapping over correctly? In the function, it has the two dates as Nullable(Of DateTime), which I provide a date, and the string is getting passed Nothing. Any ideas? Can't post any code on this one... Thanks.
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.
I have a dynamic query in the stored procedure, and the code looks something like this:
SET @section_test = 'SELECT sectioncode FROM ' + @tablename + ' WHERE sectioncode = "' + @condition + '"' EXEC (@section_test)
What I need to do is try to check if the query returns any values using EXISTS (possibly), but at the same time I don't want to return the results of that dynamic query's select statement in my stored procedure. Is it possible?
I wrote a stored procedure with three variables to be passed as input parameters. The stored procedure runs a select into statement into a temp table. The resulting temp table with another table was queried using right outer join to produce the desired results. The stored procedure compiles error free.However when I ran the stored procedure with the parameters(3) in ISQL/W (SQL Server 6.5) the headers(column-names) were displayed but no records. When runned as a query with the same parameter values, records were produced. Help please urgent.
I am rewriting several stored procedures that originally had lots of "multiplicated" code. I am aware that references to objects within dynamic SQL do not create dependencies, so I intend to add code that will generate the dependencies but will NOT produce any output in both the Results and Messages tabs, not be overly "messy" or complicated, and have the least impact on execution plan creation as possible.
As we use a dependency list of tables used to our support staff pinpoint possible data issues associated with each of these stored procedures.
I have tried a few methods already, including this:
SET @SQL = N'SELECT Column1,Column2 FROM dbo.TableName'; ... /***************************************************************************************/ /* This code block is only to establish dependency of objects used within dynamic SQL. */ /* */ /* SET statements are used so that no output is produced in Results or Messages tabs. */ /* Object existence check avoids error 208, "Invalid object name" message. */ /***************************************************************************************/ DECLARE @DependentObject SQL_VARIANT; IF OBJECT_ID(N'dbo.TableName', N'U') IS NOT NULL SET @DependentObject = ( SELECT TOP (1) Column1,Column2 FROM dbo.TableName); /* End code for dependency of objects used within dynamic SQL */
In my appllication, i am having a DataTable... For that DataTable i have to write a query for a expression... This epression is more of mathematical expression type. Here is the sample expression-
How i can write a query for such a equation...? Is it possible to use logical & mathematical operator in the equation & to write a query for this type of equation... Is there is any good article on this...
Filling a DataTable from SqlQuery : If SqlQuery returns some null values problem ocurrs with DataTable. Is it possible using DataTable with some null values in it? Thanks
hi, like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right? so, is there something that i can use to hold those records so that i can do the delete and update just on those records and don't need to query twice? or is there a way to do that in one go ?thanks in advance!
Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist. My current SQL statement is as follows. SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))" So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated. Thanks, James.
I've read some articles on generating tag clouds but so far only one actually showed a query. And the query was on a simple database with a few tags. In our database we have records that can have literally hundreds of unique tags. So, I'm wondering how to get a realistic result set of the top tags? I can't just do a group by and select the top 30 or 50 because that won't necessarily get me through the alphabet. I'd like to at least have as many letters from the alphabet in the tags as possible like (ant, cat, dog, horse, lion, seal, zebra) but if I do the top 30 it may cut off around the letter "c". Know what I mean? So, how can I generate an accurate tag cloud query that uses all available letters from the alphabet as starting letters for the tags? Thanks.
If I wanted to run a query on any table and in the recordset that is returned have an 'id' field (or whatever) with the record id of that record, how would I do this?
I'm thinking something like
Select field1, field2, recordNumber // derived somehow - not an actual field from table
What I would like to end up with is a pivot table of each account, the trigger code and service codes attached to that account, and the rate for each.
I have been able to dynamically get the pivot, but I'm not joining correctly, as its returning every dynamic column, not just the columns of a trigger code. The code below will return the account and trigger code, but also every service code, regardless of which trigger code they belong to, and just show null values.
What I would like to get is just the service codes and the appropriate trigger code for each account.
SELECT @cols = STUFF((SELECT DISTINCT ',' + ServiceCode FROM TriggerTable FOR XML PATH(''), TYPE ).value('(./text())[1]', 'VARCHAR(MAX)') ,1,2,'')
I hope I'm posting this in the correct forum. If not I apologize. I have a nested select query that I imported from Oracle:
Oracle Version:
Code Snippetselect avg(days) as days from ( select dm_number, max(dm_closedate) - max(comment_closed_date) as days from dm_data where dm_type = 'prime' and dm_closedate <= '31-dec-2007' and dm_closedate >= '1-dec-2007' and program = 'aads' group by dm_number)
SQL Version:
select round(abs(avg(days)), 0) as days from (select dm.dm_number, abs(datediff(DAY,max(dm.dm_closedate), max(dm.comment_closed_date))) as days from dm_data dm, ProgramXref px where px.Program_Name = 'aads' and dm.Program_Id = px.Program_Id and dm.dm_type = 'prime' and dm.dm_closedate <= '31-dec-2007' and dm.dm_closedate >= '1-dec-2007' group by dm.dm_number)
In Oracle the query runs fine. In SQL I am getting a "Line 10: Incorrect syntax near ')'." error. If I run just the nested portion of the query, there are no errors. It only happens when the first query tries to query the nested query. Can anyone help me get the syntax correct?
ok can someone tell me why i get two different answers for the same query. (looking for last day of month for a given date)
SELECT DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(m, 0, CAST('12/20/2006' AS datetime)) + 1, 0)) AS Expr1 FROM testsupplierSCNCR I am getting the result of 01/01/2007
-- The 3rd query uses an incorrect column name in a sub-query and succeeds but rows are incorrectly qualified. This is very DANGEROUS!!! -- The issue exists is in 2008 R2, 2012 and 2014 and is "By Design"
set nocount on go if object_id('tempdb.dbo.#t1') IS NOT NULL drop table #t1 if object_id('tempdb.dbo
[code]....
This succeeds when the invalid column name is a valid column name in the outer query. So in this situation the sub-query would fail when run by itself but succeed with an incorrectly applied filter when run as a sub-query. The danger here is that if a SQL Server user runs DML in a production database with such a sub-query which then the results are likely not the expected results with potentially unintended actions applied against the data. how many SQL Server users have had incorrectly applied DML or incorrect query results and don't even know it....?
For each customer, I want to add all of their telephone numbers to a different column. That is, multiple columns (depending on the number of telephone numbers) for each customer/row. How can I achieve that?
I want my output to be
CUSTOMER ID, FIRST NAME, LAST NAME, TEL1, TEL2, TEL3, ... etc
Each 'Tel' will relate to a one or more records in the PHONES table that is linked back to the customer.
When I run the following query from Query Analyzer in SQL Serer 2005, I get a message back that says. Command(s) completed successfully. What I really need it to do is to display the results of the query. Does anyone know how to do this? declare @SniierId as uniqueidentifierset @SniierId = '85555560-AD5D-430C-9B97-FB0AC3C7DA1F'declare @SniierAlias as nvarchar(50)declare @AlwaysShowEditButton as bitdeclare @SniierName as nvarchar (128)/* Check access for Sniier */SELECT TOP 1 @SniierName = Sniiers.SniierName, @SniierAlias = Sniiers.SniierAlias, @AlwaysShowEditButton = Sniiers.AlwaysShowEditButtonFROM SniiersWHERE Sniiers.SniierId=@SniierId
I have a query that performs a comparison between 2 different databases and returns the results of the comparison. It returns 2 columns. The 1st column is the value of the object being compared, and the 2nd column is a number representing any discrepancies.What I would like to do is use the results from this 1st query in the where clause of another separate query so that this 2nd query will only run for any primary values from the 1st query where a secondary value in the 1st query is not equal to zero.I was thinking of using an "IN" function in the 2nd query to pull data from the 1st column in the 1st query where the 2nd column in the 1st query != 0, but I'm having trouble ironing out the correct syntax, and conceptualizing this optimally.
While I would prefer to only return values from the 1st query where the comparison value != 0 in order to have a concise list to work with, I am having difficulty in that the comparison value is a mathematical calculation of 2 different tables in 2 different databases, and so far I've been forced to include it in the select criteria because the where clause does not accept it.Also, I am not a DBA by trade. I am a system administrator writing SQL code for reporting data from an application I support.
Hi,New to .Net and SQL. I have two tables that I have joined together. RentalControl_Main has the rental informationd and an Adjuster ID that links to the ADjuster table and the adjusters name. I am trying to create a report that gives the "Single" adjuster name and the totals for all of their contracts. I have a details report that gives each contract info. for each specific adjusters rentals. However, I want to just list the adjuster once and give all of their totals. In my SQL statement I have all of it written out and just need to knowwhat to do in place of 'Alex Early' that will give me all of the distinct adjusters.Do I need to code this on the page with a do while loop?Appreciate any help.SELECT SUM(dbo.RentalControl_Main.Rate) / COUNT(dbo.RentalControl_Main.Rate) AS AmtAvg, SUM(dbo.RentalControl_Main.DaysBilled) / COUNT(dbo.RentalControl_Main.DaysBilled) AS DayAvg, SUM(dbo.RentalControl_Main.Rate * dbo.RentalControl_Main.DaysBilled) / COUNT(dbo.RentalControl_Main.Rate) AS TotAvgFROM dbo.RentalControl_Main INNER JOIN dbo.RentalControl_Adjuster ON dbo.RentalControl_Main.AdjusterID = dbo.RentalControl_Adjuster.AdjusterIDWHERE (dbo.RentalControl_Adjuster.AdjusterName = 'Alex Early' AND (dbo.RentalControl_Main.DateClose IS NOT NULL) AND (dbo.RentalControl_Main.AgencyID = '2')
I was wondering if there was a keyword that would allow you to return the number of results from a query such as (this is fake just giving an example so that someone can give me the real answer)
I am a beginner with SQL, so please excuse any ignorance here.
Under SQL 6.5, when executing a SELECT DISTINCT query against a table in a certain database, the results were returned alphabetized. Now, after migrating the database to SQL 7.0, the same query does not return the results alphabetized. If I add an index for the column specified in the query to the table, the results come back alphabetized. Is there any way to correct this other than adding indexes for all columns in all tables that are queried in this manner?
I have this line of code that when run in the query doesn't return anything:
srv.AGENT_S_ACC_CODE IN ('" & Replace(Replace(Parameters!arcode.Value," ",""),",","','") & "') The parameter is setup and the query works when I hardcode it with a value but will not return anything with this, does anyone know why?
Hi guys, say i wrote a query that returns 1,000 records.. what kinda query could i write that only returns say the first 50 records of the 1,000 recs..
Hello, I want to select all the customerIDs where an email address exists. Easy: select customerid from customers where emailaddress = @emailaddress Now I want to use the resulted customerIDs from the above query as a parameter to select all the email addresses with emailstatus equal to 3. How do I create this type of while statement in a stored procedure? I prefer to not create a temporary table. My idea was to do it like this: select emailaddress from emailaddresseswhere emailstatus = 3 and customerid = (select customerid from customers where emailaddress = @emailaddress) This doesn't seems to work. I get the error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. thanks
I have a pretty big SQL query with a one to many sort of relationship... There are client accounts that we're reporting on. Each account has four different historical categories attached. Each historical category can have maybe fifty entries in each, sorted by date. I need to figure out how to grab the unique accounts and show only the three most recent results per each historical subcategory with the account... the three most current results from each of the four subcategories, displayed by the parent client account number. I've created four views to isolate the subcategories as a start, thinking I could bring them into a parent query ... but my question would be... how do I generate JUST the top three historical transactions by account number? If I select TOP 3, I get only the 3 newest in the MASTER LIST, not per client account, which is what I need to do. Does this make sense? I could really use a good SQL helping hand with this one. Thank you!