How to rename a column in a SQL Server Query - sql-server

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;

Related

Automatically produce aliases for all columns in SELECT statement

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 ?

T-SQL Query for Setting Column Aliases

I'm after a way in SSMS of writing a query that will concatenate Table & Column to give me a much more readable Alias.
I'm actually using SSMS, right clicking on views in the object explorer, and selecting new view.
I select the tables I require from the list of available tables.
I then set the joins required in the SSMS diagram pane, and select all of the columns I want from the various tables.
In the criteria pane, I can see the Column, Alias, and Table columns.
It's fine all the time the value in the Column column is unique, for example:
Column = RequestedDeliveryDate
Alias = (blank)
Table = Stock Item
BUT!
As soon as the column value is NOT unique, SSMS assigns its own alias, for example:
Column = AddressLine1
Alias = Alias1
Table = Customer
Column = AddressLine1
Alias = Alias2
Table = Supplier
These are pretty hefty views that I'm dealing with, so SSMS assigns a lot of Aliases, which is not a problem in itself, but makes select statements in my Visual Studio project, much more unreadable:
SELECT RequestedDeliveryDate, Alias1, Alias2 FROM vwMyView
All that I'm after is some way in SSMS of writing a query that will concatenate Table & Column to give me a much more readable Alias:
Column = AddressLine1
Alias = CustomerAddressLine1
Table = Customer
Column = AddressLine1
Alias = SupplierAddressLine1
Table = Supplier
This would make my SELECT queries much more readable:
SELECT RequestedDeliveryDate,CustomerAddressLine1,SupplierAddressLine1 FROM vwMyView
I can manually assign an alias in the Criteria Pane, but it's very tedious across many views with many duplicate column names.
I hate the view designer. Just create the view with code only. Eg:
CREATE VIEW [dbo].[MyViewName]
AS
SELECT RequestedDeliveryDate,CustomerAddressLine1,SupplierAddressLine1 FROM vwMyView
GO
Copy the joins and filter from the view designer if you like, but then change the field aliasing in the SELECT section.

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 ?

Derby Database Table Column Name Format Inconsistent in Query

When query a Derby database, I find out that for some tables I have to double quote the column name and use table name to qualify the column name, but for some other tables I don’t need to. What happens to these tables and how can I make all tables the same and can query them without the double quote and the table name qualifier? I am using NetBeans IDE’s Sql Command tool. Below are those different queries.
Set schema app;
Select * from table1 where table1.”state” = ‘CA’;
Select * from table2 where state = ‘CA’;
Putting a tablename or column name in quotes, sometimes referred to by the jargon-y term "delimited identifiers" does two things:
Allows you to use words that are otherwise reserved keywords (e.g., naming a column "WHERE" or "SELECT")
Instructs the database system to process the name using case sensitive rules, rather than case-insensitive rules
So if you originally created "table3" with a CREATE TABLE statement that specified "table3" in double quotes like this, then you will forever after have to refer to it with the name in double quotes.
select * from table3
will be automatically processed by the database as if it was
select * from TABLE3
while
select * from "table3"
will successfully match the table you created as create table "table3"
See: http://db.apache.org/derby/docs/10.9/ref/crefsqlj34834.html

Copy table data and populate new columns

So I'm trying to copy some data from database table to another. The problem is though, the target database table has 2 new columns that are required. I wanted to use the export/import wizard on SQL Server Management Studio but if I use that I will need to write a query for each table and I can only execute 1 query at a time. Was wondering if there are a more efficient way of doing it.
Here's an example of 1 table:
dbase1.dbo.Appointment { id, name, description, createdate }
dbase2.dbo.Appointment { id, name, description, createdate, auditby, auditat}
I have a total of 8 tables with those 2 additional columns. and most of them are related to each other via fk, so I wanted to use the wizard as it figures out which table gets inserted first. The problem with that is, it only works if I do a "copy data from one or more tables " and not the "write a query to specify data" (I use this to populate those two new columns).
I've been doing this very slow process in copying data as I'm using MVC Code First for my application and I dont have access to the server to be able to drop and create the table at my leisure. So I have to resort to this to maintain the data that I already have.
An idea: temporarily disable the foreign key constraints in the destination database. Then it doesn't matter what order you run your inserts. In order to populate the two new and required columns, you just need to pick some stock values to put in there (since obviously these rows initially are not subject to initial auditing). For example:
INSERT dbase2.dbo.appointment
(id, name, description, createdate, auditby, auditat)
SELECT id, name, description, createdate,
auditby = 'me', auditat = GETDATE()
FROM dbo.appointment;
Since it seems the challenge is merely that the destination requires columns that aren't in the source, and that you need to determine what should be populated in these audit columns, this seems to solve multiple problems at once. You just need to figure out what to put in there instead of 'me' and GETDATE().
(To get the wizard to pull these 8 tables for you, you might be able to create a view similar to the select portion of the above query, but that's more work and it won't see the underlying FK constraints to generate them in the right order anyway.)
Write the sql query for each of the insert processes in the order you want it. That would be the simplest approach.
Set the Default values for these two columns
Like for AuditAt - Default Date i.e. GetDate()
For AuditBy - The Person ID/Name
Now, you can Insert into these tables without entering for these two columns

Resources