Change Column location of SQL statement in Excel - sql

Within excel I have connected my Microsoft SQL Server database to it, to display results. The system I have set in place is built off of a form. If a user chooses option 1, the query results will show:
Select person, car, house from mytable1
If the user chooses option 2, the query result will show:
Select job, person, land, truck from mytable2
The very first select statement will give me a table in the column order in which I would like it. However, as a user uses the form again, it will re-query it to use which ever select statement is requested. When the re-query happens the column order which items are shown are in different areas. Even if the select statment is stated within the same order. Is there a way in which I could order the columns in a specific order?
I've attempted to unchecked "Preserve Column Sort" within the Data Range Properties, but ends up leaving empty columns. I.E. : Column1, Column2, Column3, etc.

You may already know this, but since Excel allows you to move the columns in a table / ListObject around, it seeks to preserve any changes you make. So, if you run a query:
select one, two, three
And then move the column "three" in front of "one," when you re-run your query, it will keep them in that order in the ListObject, even though the query said otherwise.
This also means if you add a column, no matter where you add it, it will go to the end when MS Query renders the output.
select four, one, two three
("four" goes to the end in Excel, even though it was listed first in SQL)
In your example, the column "person" was common across the two queries, so Excel (MS Query) would move it to the first position and put all other columns after that.
When Excel deletes the old columns, it leaves a tracer behind -- you may notice the columns that follow your table aren't the normal size; they are the size of the fields that were deleted. I call them "ghosts."
This is a serious hack, but the only way I know of to alleviate this problem is to run a bogus query (ie select 1), delete the ghosts -- remove the entire columns, and then run your second query. Here is some ugly code I use in VBA to do this:
Dim lo As ListObject
Set lo = Sheets("Sheet1").ListObjects("Table_ExternalData_1")
Range(lo.HeaderRowRange.Offset(0, lo.HeaderRowRange.Columns.Count), _
Range("XFD1")).EntireColumn.Delete
Yes, this deletes every column after the table, which means if there is useful data above or below the table in columns after the table, those are wiped out.
Maybe there is a better way -- I'm curious to see if you get any other solutions.

Related

T-SQL selecting all col to update in merge

Maybe that stupid question, but I don't know how to describe my problem to uncle google.
I have two simple tables with 3 rows: ID, Name, SomeVal;
Now I want update them with merge, and that's simple:
MERGE Locations T
USING Locations_2 S ON T.ID=S.ID
WHEN MATCHED THEN
UPDATE
SET
T.Name=S.Name,
T.SomeVal=S.SomeVal;
Ok, that works, but I wrote every column name by hand. So, when I want to update for example table with 30 columns, writing everything by hand will be painful. So, is there any option to update every column in the table no matter how many columns it has?
I tried "*". It is UPDATE SET T.*=S.*, and that didn't work.
What I normally do when I want to be time efficient (or lazy, depending on your view) is this:
Run this command:
sp_help TableName;
Copy/paste the first column, then hold down Alt whilst dragging the mouse cursor in front of the column names. This way I can then type one comma in front of all the fields. Then I do the same after the field name except with an = sign.
That's the only shortcut I can think to help you, and has saved me hours of typing over the years.
No. Merge statements are very verbose. You can hack a shortcut by scripting your table as CREATE, copy the column names using SHIFT + ALT to select a large swath of them, then paste them into the MERGE query, hit space, add the = sign, then paste again.
The statement is one direction, (i.e., you can't update S with T; only T can be updated) so you don't strictly need to provide the source/destination alias for each column.

MS Access: Conditional formatting - highlight duplicates

Is there an expression that I can use in MS Access ,to highlight Duplicate entries in Reports?
I tried something like Expression is : Count(*)>1 but it doesn't work.
Br,
I suspect that the original query will need to be bulked up with a sub-query that has an ID column and count of ID. The outermost query will then need to also return the ID count.
Within the report you'd then need add another field that would show the linked ID count if it was > 1.
Access reporting (and forms) allows conditional formatting to be used in a similar way to excel.
See Ribbon: Report Design Tools>Formt>ControlFormatting...
It will let you change the format of a control depending on the value it, or another control, contains.
It's a very nice feature and will also let you add bar charts to you list forms to graphically represent the values sorted in a control.
However, the data set will need to have a column that indicates whether the current row has duplicate records. The snippet from you current query that you provided (that I repeat below) will not do this:
...OR (((Object.Key) In (SELECT [Key] FROM [Object] As Tmp GROUP BY [Key] HAVING Count(*)>1 )));
Without seeing the whole query I can't really help much, but you will need to remove the use of IN and make the SELECT statement a subquery of the main SQL Statement. The main query resultset will need to be LEFT JOINED to the sub query using the Key field. Because of the LEFT JOIN you can use "isnull(Key)" in the SELECT clause and isnull(Key) will be true for non-duplicate rows.
You can then refer to thiscolumn in your conditional formatting
I hope this makes some sense.
You
For a quick and dirty way to highlight duplicate data:
Select the object you want to highlight if it's duplicated, and make
the background white (or whatever the colour of your background is).
Create a copy of the object that you want highlighted if it's
a duplicate.
Format the copy so it has a highlight, and/or add extra text
(eg: DUPLICATE)
Put the copy behind the original (so it can't be seen).
On the original object, select "Hide duplicates" in properties.
Ensure "Hide duplicates" is NOT selected on the copy.
So when the duplicate appears, Access will hide it, but then the object you've created that was originally hidden beneath now becomes visible - effectively highlighting the field.
(Unfortunately it will only highlight the field itself, not the entire section.)

best aproach to distinct query result before importing it into Excel cells

I have a query which grabs data from Access with contents:
A,1,z
A,2,z
B,1,y
A,1,i
I created 3 dropdowns in excel and I want to populate them with rows from these columns. The problem is that in each column there are duplicates and I want to get rid of them. I am looking for a solution to get rid of these duplicates.
Current process is following:
run a query. I use VBA in Excel. Access is being queried.
paste results into a separate sheet (it takes A LOT of time because there are 20k reocrds)
assign a range for my dropdows
As you can see my second step is very resource hog and the proccess time should drop drastically by removing duplicates from each column.
What is the best approach to populate dropdowns with unique values from query?
My ideas
create a query which will output me:
A,1,z
B,2,y
, ,i
In that case i will not have to distinct values manually in excel. Not possible to do, as I understand...
Add values from each columns to List, remove doubles, paste result into excel. This is my personal favorite because I see no other ways to fix the issue.
create multiple queries to DISTINCT each table_column separately.. Not very fast solution, I suppose
some other approach
Run three SELECT DISTINCT Colx FROM table queries to get the values for the three dropdowns. Your option two. The work has to be done sometime so you might as well use the tools designed to do the work instead of reinventing that wheel.
If you use select distinct columna, columnb... instead of select columna, columnb... you will get what you want. The SQL will take longer to run, though.

Use columns.add(...) in Word with non-uniform column widths?

Problem I'm having is that table.Columns.add(ref Object BeforeColumn) requires a reference to another column in the table. However, when I try to access the last column in the table to pass as a reference using table.Columns.Add(table.Columns[table.Columns.Count])
I get the error:
"Cannot access individual columns in this collection because the table has mixed cell widths."
As my current work around, I catch the error, and call table.Columns.DistributeWidth() to make sure the columns are uniform and run the rest of the code. However, I lose the formatting of my cell widths this way, which is unfortunate.
Is there any way I can workaround this without losing the cell width?
(I realize one way is to store every cell's width before running this process, and then re-applying the widths afterward, but this seems like a very costly solution to something that should be simpler)
I've found one way to do it. Here's how I approached it.
*Caution, I'm assuming that the table is uniform. i.e. The number of columns is the same across all the rows. (Note, the API has a Table.uniform function, but the description is not complete. In the API it says "True if all the rows in a table have the same number of columns." However, it also checks if the columns have uniform width).
Instead of using table.Columns.Add(table.Columns[table.Columns.Count]) to add a column before the last below, I select a cell in the table and used the insert command:
//assuming table is the name of the table you want to add columns to
table.Cell(1, table.Columns.Count).Select();
word.Selection selection = table.Application.ActiveWindow.Selection;
selection.InsertColumns();
This might actually be a better way to add columns, as the api gives you way more options on how to insert (i.e. use InsertColumnsRight to insert to the right of the column). The Columns.Add(...) function by default inserts to the left of the select

How does Access's query editor decide whether to discard my formatting?

Like a lot of developers who are comfortable with SQL syntax I get frustrated when working with Access's query editor. I'm talking about the raw SQL Syntax view, obviously.
One of its many annoying properties is that upon saving it will discard my layout / formatting. When reopening the query all I see is a bunch of unformatted SQL.
However, if my syntax is long and/or complex enough I've noticed that Access will retain my formatting and layout and, oh joy, the query remains clear and readable. I'm looking at an example right now with a page of SQL containing couple of UNIONs all nicely laid out from a few days ago.
At what point does Access flip over to allowing the user to retain his own formatting? Is it length? Complexity? And is there maybe even a trivial structural edit (if trivial structural isn't an oxymoron) I can make to all my queries which will force Access to leave my layout in place?
There are certain things that Access' query editor is not able to display in design mode.
Queries with UNION are the only thing that come to my mind right now, but there are probably more.
In my experience, Access always changes the layout as long as it's able to display the query in design mode.
As soon as you put something in the query that Access can not display in design mode (like UNION), Access leaves your layout and formatting as it is.
I couldn't figure out why Access kept changing my format in a union query (but not for every query or table included).
I simply created another SELECT query based upon the Union query and corrected everything in design view. It's a lot easier.
When I created the SELET query based upon the UNION query, I included tables or queries that I used as lookup tables and had formatted a field to select the second column from a record in a lookup field that the ubion query had anoyingly converted back to the first field in the selected record (usually the ID No of the record).
For example, I might lookup the account name in a record in the cash disbursements table that should display "Office Supplies Exp" but the Union Query converts at least one of the queries or tables I have combined in the union query to the Account Number, the first record in the lookup table, which was originally hidden in the lookup field.
Just to add to Christian's answer, I've done some more testing and find that UNION and DDL queries are left alone by Access.
If we add Pass through queries to that list, then that would match the queries deemed SQL Specific on the menu:
So, those would seem to be the three special cases.
Before saving just type the word union before the ;.
After opening Access next time, remove the word union and start working. When you want to save, first type union again.