Automatically produce aliases for all columns in SELECT statement - sql-server

I'm using Microsoft Query to pull data from MS SQL Server to Excel. Many of my tables have the same column names, for example:
[task].[active]
[user].[active]
[task].[name]
[user].[name]
When I pivot in Excel, only the column names are shown. A pivot filter might have multiple fields called "active" which is very confusing.
I'd like to alias every column with the table name it's from, so that in the filter it would say "task_active" and "user_active". My Excel SELECT statement would be:
SELECT active AS task_active, name AS task_name FROM task...
Is there a quick way to prepend the table name to an alias using a formatting tool? I have Apex SQL Refactor, and Notepad++ but I haven't found a way to do this without having to manually type all of the column names again.

If you populate resultset to datatable then datatable to excel then it will automatically change duplicate column name to col1,col2 etc.
This is not your requirement.you want it to be specific.
Method 1 . Create temp table with desire column name
Insert the result in #temp table
Return #temp table result set
Method 2 : Use dynamic query.
Wht your real query look like ?

Related

How to rename a column in a SQL Server Query

If I do SELECT name, ISNULL(license, 0) FROM table; I get a resulting table with the license column having no name ("Column1" on my xml), how do I give it a name in the query so it makes my life easier when manipulating it on my application? I tried finding it but could only find how to rename the column on the table itself, instead of renaming the column on the table generated by the SELECT.
To simplify: ISNULL removes the name of the column in the generated by my SELECT and I want to bring it back.
Just use an alias:
SELECT name, ISNULL(license, 0) AS license FROM table;

Power Query to Filter a SQL view based on an Excel column list

Is there a way to filter a SQL view based on a list of values in an excel table column using Power Query?
I have a SQL view that returns a large set of data (millions of records or properties). Users want to filter that based on an excel table column of property IDs. I know I can just do a merge join based on the property ID between the view and the excel column in power query. But it looks like the merge brings in the millions of records first then filtered it in the join. Which takes a long time. Users want to change the list of propertyIDs on the fly on a daily basis and run the query.
Essentially, I wanted to create in Excel power query
what is in SQL
SELECT * FROM SQLViewName
WHERE PropertyID IN (Select Column from ExcelTable)
You should be able to do this with a List.Contains function.
If my ExcelTable is
ID
---
436
437
438
439
then adding a filter like this should do the trick:
Table.SelectRows(SQLViewName, each List.Contains(ExcelTable[ID], [PropertyID]))
When I tried this and did View Native Query on the last applied step, it folded the Excel table into a WHERE clause with the ExcelTable values as literals like this:
select [_].[PropertyID],
[_].[OtherColumns]
from [dbo].[SQLViewName] as [_]
where [_].[PropertyID] in (436, 437, 438, 439)
This allowed me to load a multi-million-row table in just a couple seconds.

Get a list of columns and widths for a specific record

I want a list of properties about a given table and for a specific record of data from that table - in one result
Something like this:
Column Name , DataLength, SchemaLengthMax
...and for only one record (based on a where filter)
So what Im thinking is something like this:
- Get a list of columns from sys.columns and also the schema-based maxlength value
- populate column names into a temp table that includes (column_name, data_length, schema_size_max)
- now loop over that temp table and for each column name, fetch the data for that column based on a specific record, then update the temp table with the length of this data
- finally, select from the temp table
sound reasonable?
Yup. That way works. Not sure if it's the best, since it involves one iteration per column along with the where condition on the source table.
Consider this, instead :
Get the candidate records into a temporary table after applying the where condition. Make sure to get a primary key. If there is no primary key, get a rowid. (assuming SQL Server 2005 or above).
Create a temporary table (Say, #RecValueLens) that has three columns : Primary_key_Value, MyColumnName, MyValueLen
Loop through the list of column names (after taking only the column names into another temporary table) and build sql statement shown in Step 4.
Insert Into #RecValueLens (Primary_Key_Value, MyColumnName, MyValueLen)
Select Max(Primary_Key_Goes_Here), Max('Column_Name_Goes_Here') as ColumnName, Len(Max(Column_Name)) as ValueMyLen From Source_Table_Goes_Here
Group By Primary_Key_Goes_Here
So, if there are 10 columns, you will have 10 insert statements. You could either insert them into a temporary table and run it as a loop. If the number of columns is few, you could concatenate all statements into a single batch.
Run the SQL Statement(s) from above. So, you have Record-wise, column-wise, Value lengths. What is left is to get the column definition.
Get the column definition from sys.columns into a temporary table and join with the #RecValueLens to get the output.
Do you want me to write it for you ?

Setting alias name from a subquery in SQL

In my Select query I just want to to set the alias name of a column based on a sub-query (that is, a value in another table). Is this possible in SQL Server 2008?
Like:
SELECT tax_Amt AS (SELECT tax FROM Purchase.tblTax WHERE tax_ID=#tax_ID)
FROM Table
Any way to achieve the above query?
No, you cannot dynamically set an alias or column name in standard SQL.
You'd have to use dynamic SQL if you want: but note the alias applies to the column therefore all rows have the same alias. You can't vary the alias row by row
Personally, I'd have an extra column called "TaxType" or such because it sounds like you want to vary the name per row. I'd do that anyway even if all rows have the same alias so my client code expects "TaxType"
Try like this:
SELECT (SELECT tax FROM Purchase.tblTax WHERE tax_ID=#tax_ID) AS tax_Amt
FROM Table

how to get name of column(s) causing error "Column name or number of supplied values does not match table definition"

I want to insert data from one table into another. Both tables have about 100 columns.
They don't have the same structure, but "almost": the source table has about 20 columns fewer- some of them are NOT NULL. For those columns, I have to define a default, of course.
My first trial resulted in an error message (surprise surprise):
Column name or number of supplied values does not match table definition
But in my complex case, this message is not really helpful. Is there a way to get a more precise error message?
Suggest making your query easier to read, rather than relying on the error message from the RDBMS. One thought:
Put each column on its own line.
INSERT INTO TargetTable (
Col1,
Col2,
....
)
SELECT
Col1,
Col2,
....
FROM SourceTable
create a new Excel sheet.
In SQL Server Management Studio, Alt-F1 your TargetTable; copy-paste the Column_name (and perhaps the Nullable values) into Excel sheet's ColumnA.
Copy/paste the TargetTable columns into ColumnB.
Run a macro or visually inspect/adjust the differences. The nullables you mention, you'll have to know offhand.

Resources