.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

Adding Rows to a query from another query, while avoiding UNION

Posted By:      Posted Date: April 10, 2011    Points: 0   Category :


I've looking into PIVOT and UNPIVOT which I don't believe will work, and utilizing an OUTER APPLY may work, but hamfisted attempts have not yet been successful.  The database I'm working on is stupid, pointless, frivolous, and mostly just a learning tool for me to figure a few things out, while having fun with one of my video games.  So, to get the embarrassing aspects out of the way, the database is a Move/Combo list for characters in Mortal Kombat 4.  (yes, i know, don't ask).

I lined it up as several list tables (basically what i call tables that rarely if ever change, but are used as parent tables in FK relationships.  A good example is lst_Buttons.  THis is the list of U,D,F,B,HP,HK with a description, Abbreviation and PK ID integer.  Once the buttons are added to this table, they are never messed with again, but having them in a table makes it easier to link them into the junction table of tbl_Moves and lst_Buttons, called tbl_MoveKeys.  So, like a basic move is Jump Kick,thus tbl_Moves has ID: 1, Move: 'Jump Kick'.  tbl_MoveKeys has MoveID 1, ButtonID 1, MoveID 1, ButtonID 6, and thus a silly little formatting function returning an NVARCHAR for a computed column in tbl_Moves is Command: U+HK.

I then have several other table like Locations, Weapons, Combos, and Characters. Now, understandin

View Complete Post

More Related Resource Links

MS SQL Server: Search All Tables, Columns & Rows For Data or Keyword Query

If you need to search your entire database for specific data, this query will come in handy.

So when a client needs a custom report or some sort of custom development using Great Plains, most of the time I will have to track down the data in the system by running this query and find the table(s) it is in.

adding parameter to query string


hi all,

how do i add a new parameter to an existing query string?


now i need to add a new parameter say, showsearch.

Linq Query Union

HelloI need to use Union for below Linq queries. I could use Union it if it was simple "select new whith{" but Now that I Specified Class, I encounter Error using unionDim CStep() As New List(Of ProductModel) CStep= (From p In db.Produts _ Where p.CategoryID= 1 _ Select New ProductModel() With { _ .ID = p.ProductID, _ .Name = p.Title, _ } Take (5)).Union (From p In db.Produts _ Where p.CategoryID= 2 _ Select New ProductModel() With { _ .ID = p.ProductID, _ .Name = p.Title, _ } Take (5)).ToList()

Returning rows not found in inner query

select * FROM [C_Accessioning].[HL7].[GMessages] where MessageID not in (Select MessageID from HL7.ORM_MSH) There are two rows of data in GMessages: MessageID MessageDateTime              Filename 28             2010-09-07 16:29:02.543    ORM1.hl7 29             2010-09-07 16:29:07.547    ORM2.hl7 There is no data in ORM_MSH. Please see sql statement copied above. The inner query returns null, I am expecting that the query return both rows from GMessages, but it does not return any rows. Please let me know how to fix.   Thanks,Deep

Query to return TOP n with 'Other' grouping for all remaining rows

Hi all, I've been given a specific type of report to produce, and am having difficulty in getting my SQL right to return the data as needed. I need to return TOP n Categories based on amount of sales (which I can do) but then a final category with a sum of all other sales. The purpose would be to capture all of the small sales values into one 'Other' category so that the chart I'll produce does not have lots and lots of small-value columns. I found the following post which seems to come close: SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc UNION SELECT -1, 'Other' [CompanyName], SUM(GrossSales) [GrossSales] FROM CompanySales WHERE CompanyID NOT IN ( SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc ) But this gives a syntax error on UNION, which I'm guessing is due to the ORDER BY clauses. However I think the ORDER BY is needed to ensure I return the results in the correct order. Does anyone have any ideas of how to do this? Thanks for any assistance Matt

Avoiding a SELECT distinct query generated by SSAS when using dimension derived from fact table

Hi, I am using a dimension derived out ot a fact table and the factt able primary key is dimension key. Issue is, there are large number of rows and so many attributes. SSAS issues distinct query and it takes large amount of time. Without the distinct statement, query takes only 3 min for 4 million rows. With the distinct, it takes 20 min. Becuase the fact primary key is the dimension key there is no need of a distinct statement. I know there is a option in the dimension to say "By Table" to avoid this. But unfortuantely, i breach the 4 GB limit for strings. Any suggestions for optimization? Thanks,  Sambath

Adding a table or view multiple times when building a query with BI Report Designer and Report Build

How can I add a table/view multiple times to a single query by using BI Report Designer or Report Builder 3.0? In Report Designer I managed (workaround) to add one table multiple times by creating multiple Named Queries and having the same SELECT. Still I don't know how to add one table multiple times in Report Builder 3.0.

function or query to return continuous span of months $ years as rows in query



I am using SS2008.

There are many situations in which I need to return a table where the rows are EVERY calendar month between two dates, not just the months where there is data present.

Is there a function that would take a beginning and end date mmddyyyy which would do this?

For example if I wanted 1/2004 through 8/2010?




and so on to





Thanks in advance,




Query returns correct rows but I am not able to concatenate the rows into a variable :(


Hi all,

Why in the code below I am able to list all rows and display the field 'stepID' but I am not able to concatenate them all in the variable @stepIds?

declare @date as datetime
set @date = '2010-09-20 23:01:20:000'
declare @instance as uniqueidentifier
set @instance = '04658F34-CBF1-4CCD-A683-F23BDB669D35'

  Declare @CrLf char(2)
  Set @CrLf = Char(13) + Char(10)
	Declare @stepIds varchar(8000)
	Set @stepIds = ''
		--@stepIds = @stepIds + ' - Step: ' + CONVERT(varchar(4), stepID)

Adding a new column in update query


Hi all,


Is it possible to add a new column in an update query? I am joing two tables  with [Encountered Month] from Table 1 and [Calendar Date] from table 2 and trying to add one column[Fiscal Month] into the first table where  dbo.table1.[Encountered Month]=dbo.table2.[Calendar Date]

Appreciate your help.

Help :Is this Query right? How to Get the Result: Which to use union OR join AND How?

Can you please help me?


SELECT COUNT(T1.ID) AS T1_COUNT,convert(date,DATEADD(dd, 7-(DATEPART(dw, T1.TIME)), T1.TIME),101) AS T1_TIME FROM TABLE_1 AS T1,TABLE_2 AS T2 WHERE T2.ID=T1.ID AND T1.STATE != 'C' AND T1.TIME BETWEEN '2010-01-01 00:00:00' AND '2010-09-25 23:59:59' AND PRTY='F' GROUP BY convert(date,DATEADD(dd, 7-(DATEPART(dw, T1.TIME)), T1.TIME),101) ORDER BY T1_TIME DESC

T1_COUNT ---------- T1_TIME
3 ---------------- 2010-09-25
4 ---------------- 2010-09-18
2 ---------------- 2010-09-11


SELECT COUNT(T1.ID) AS T2_COUNT,convert(date,DATEADD(dd, 7-(DATEPART(dw,T1.TIME)), T1.TIME),101) AS T2_TIME FROM TABLE_1 AS T1,TABLE_2 AS T2 WHERE T2.ID=T1.ID AND T1.STATE != 'C' AND T1.STATE ='E' AND T1.TIME BETWEEN '2010-01-01 00:00:00' AND '2010-09-25 23:59:59' AND PRTY='F' GROUP BY convert(date,DATEADD(dd, 7-(DATEPART(dw, T1.TIME)), T1.TIME),101) ORDER BY T2_TIME DESC

T2_COUNT ---------------- T2_TIME
1 ---------------- 2010-09-25
2 ---------------- 2010-09-18

Sample Query:

SQL Query Multiple rows Top problem.

This is a simplified example of my problem.
I have a Product table, and a ProductSupplier table.  A Product can have multiple Suppliers; these suppliers are ordered according to a sort order field and each has an associated price for the Product.

I want to run a query to return all my products, along with their first supplier and the cost against this supplier.

Currently the only way I can do this is by performing select statements in the manin select clause to retrieve the supplier information.






Select second query if first query returns no rows



I need to return result of the second select statement if the first select statement returns nothing:

-- First statement
SELECT Salesmen.SalesmanID, Salesmen.FullName, 
  Salesmen.AssignedAppointments, Salesmen.Picture, 
FROM Appointments INNER JOIN
  Salesmen ON 
  Appointments.SalesmanID = Salesmen.SalesmanID
WHERE (Appointments.Closed = 1)
ORDER BY Salesmen.AssignedAppointments
-- Second statement
FROM Salesmen
ORDER BY AssignedAppointments

SQL 2008 SP2: adding a "persisted computed column" creates an "Internal Query Processor Error: The q

Hi, a simple (and long-existing) stored procedure started throwing this error after adding a persisted computed column on another table that is not used in the stored procedure (but is referenced by a foreign key in the table used in the stored proc.)
Msg 8624, Level 16, State 1, Procedure pSetPersonExtraAnswer, Line 26
Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services.

I think I have traced the "culprit" to the following update.
ALTER TABLE dbo.Persons ADD fullName AS (firstName + ' ' + lastName) PERSISTED

Here is the very weird thing:

If I restore the DB, immediately add the persisted computed column and run the problematic SP call, I get the error in Management Studio.

If I restore the DB, run the problematic SP call and then add the computed column, I no longer get an error from SSMS when I rerun the SP call. But, I still get it from my ASP.NET (via enterprise library) code!

When the error happens, altering the pro

Group by Clause in Union Query


Table 1

Qty BatchNo MaterialCode

54 211 127

50 AR0347 165

252 054 190

180 022 191

50 HP10004 194

20 005010 196


Table 2

Qty BatchNo MaterialCode

6 211 127

28 054 190

20 023 191


Select Sum(iQty) as iQty ,vBatchNo,vMaterialCode




 a.iQty as Qty,      

 a.vBatchNo   as  BatchNo,      

 a.vMaterialCode &

Programaticly Adding Conditionals to a Gridview Query


I have a gridview databound to an sql source returning about 1300 records (cars).  I have listboxes to narrow the search (model year, manufacturer, segment).  What is the most efficient way to tie these listbox selections to the gridview query?


Right now I am piecing together my own sql query string and replacing the SelectCommand.  This works, but I keep running into timing issues where the command reverts back to the coded initial value.  I can continue debugging this, but is there a better way?

Using Union and Order in query


SQL Server 2008. Guys,  I need to do following. I have tables Employees(empid,country,region,city) and Suppliers(supplyid,country,region,city). So I have a query:

SELECT country, region, city
FROM HR.Employees


SELECT country, region, city
FROM Production.Suppliers;

So I need

to add logic to the query 
such that it would guarantee that the rows from Employees
would be returned in the output before the rows from Customers,
and within each segment, the rows sh
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend