select value into variable and alias in SQL Server - sql-server

I'd like to simultaneously do two things in an MSSQL query:
select a field's value into a variable
select #myvar = colName from tableName
alias my column
select colName as [myCol] from tableName
I've tried these things:
Attempted Syntax select #myvar = colName as [myCol] from tableName
Attempted Syntax select #myvar = (colName as [myCol]) from tableName
Attempted Syntax select (#myvar = colName) as [myCol] from tableName
checked select statement syntax: https://msdn.microsoft.com/en-us/library/ms176104.aspx
If this is possible, how can it be accomplished?

A select can either assign values to variables or return column values, but not both.
In some cases, e.g. when using select to provide data to an insert, an output clause may be useful. A tool well worth having in your pocket as it provides access to identity values from insert and both before and after values when used with update.

Related

It is valid to write SELECT 'a' colName in TSQL, what is the alternate in PL/SQL?

If I write SELECT 'a' colName UNION SELECT 'b' colName in TSQL, it returns a temporary table form and I can use it later in my stored procedure, as well what is the alternate in PL/SQL?
In Oracle, you must always select from a table.
Fortunately, they have provided a table especially for queries like the one you want to write - the dual table.
Your query would therefore become:
select 'a' colname from dual union all
select 'b' colname;
Note that I've changed the union to a union all, to avoid unnecessary sorts/distincts.
If you're going to be using this in PL/SQL, it very much depends on what you're going to do with the results as to how you would code it.
If you're going to use the results to do some DML, e.g. insert into a table, you'd just do it in a single DML statement, e.g.:
begin
insert into some_table (some_column)
select 'a' colname from dual union all
select 'b' colname from dual;
end;
/
If you're going to use it to do something that can't be done in a single DML statement, you're going to need to return the values into something. That could be looping through a cursor, or it could be returning into a collection, e.g.:
begin
for rec in (select 'a' colname from dual union all
select 'b' colname from dual)
loop
dbms_output.put_line('colname = '||rec.colname);
end loop;
end;
/
or
declare
type t_vals is table of varchar2(1);
v_vals t_vals;
begin
select colname
bulk collect into v_vals
from (select 'a' colname from dual union all
select 'b' colname from dual);
end;
/
TSQL and Oracle SQL both are developed based on SQL. But they have some differences with each other. One of the key differences that related to your question, is the minimum structure of a SELECT statement.
SQL says that a SELECT statement minimally should be in the following form:
SELECT expressions FROM table
Oracle SQL also defines the same rule for the SELECT statement in minimum.
In PL/SQL:
SELECT ... [BULK COLLECT] INTO ... FROM table
But TSQL, changes this rule and says that a SELECT statement minimally could be constructed as below:
SELECT expressions
Finally, in Oracle SQL you need to execute a SELECT statement against a relation such as Table, but in TSQL you can execute a SELECT statement without using any relation.(For example: Selecting a constant)
i think he is just asking how to rewrite
SELECT 'a' colName UNION SELECT 'b' colName
in pl/sql.
So this is the answer
select 'a' colname from dual union all
select 'b' colname from dual ;
Read more

SQL Query Results to Local Variable without unique identifier

I'm relatively new to SQL and I'm trying to write a query that will assign the result of multiple rows into a local variable
DECLARE #x VARCHAR(MAX)
SET #x= (SELECT someCol
FROM table)
--Does important stuff to the #x variable
SELECT #x
During my research I realized that this won't work because the subquery can only return one value and my query will return multiple results. However I can not do something like this:
DECLARE #x VARCHAR(MAX)
SET #x= (SELECT someCol
FROM table
where id= 'uniqueIdentifier')
--Does important stuff to the #x variable
SELECT #x
The reason I can't use a where clause is that I need to do this for the entire table and not just one row. Any ideas?
EDIT: I realized my question was too broad so I'll try to reformat the code to give some context
SELECT col_ID, col_Definition
FROM myTable
If I were to run this query col_Definition would return a large varchar which holds a lot of information such as the primary key of another table that I'm trying to obtain. Lets say for example I did:
DECLARE #x VARCHAR(MAX)
SET #x= (SELECT col_Definition
FROM myTable
WHERE col_ID = 1)
--Function to do the filtering of the varchar variable that works as expected
SELECT #x as [Pk of another table] --returns filtered col_Definition
This will work as expected because it returns a single row. However, I would like to be able to run this query so that it will return the filtered varchar for every single row in the "myTable" table.
If I understand correctly, you store a PK embedded in a string that you want to eventually get out and use to join to that table. I would think putting the group of records you want to work with into a temp table and then applying some logic to that varchar column to get the PK. That logic is best as set based, but if you really want row by row, use a scalar function rather than a variable and apply it to the temp table:
select pk_column, dbo.scalarfunction(pk_column) as RowByRowWithFunction, substring(pk_column,5,10) as SetBasedMuchFaster
from #tempTable.
You need to define what the 'uniqueIdentifier' is first.
Not sure about using a subquery and grabbing the result and executing another query with that result unless you do an INNER JOIN of some sort or if using python or another language to process the data then use:
("SELECT someCol
FROM table
where id='%s'" % Id)

Resolving Ambiguos columns without Ailas

I have a Dynamic query where the select columns are dynamically prepared. As this is a common code and I have some specific column choices, I have to put Aliases according to my query.
For this I had to use string replace.
I want to know if there is a provision in SQL Server to resolve the ambiguous columns without Alias.
i.e. Something like take values always from Table1 when there is ambiguity.
DECLARE #ColumnNames VARCHAR(1000)
DECLARE #SQLStmt VARCHAR(MAX)
--Below I am getting list of column names comma separated 'Id,Name,Salary'....
SELECT #ColumnNames = testDB.dbo.testfuncion(45)
SET #SQLStmt = 'SELECT '+#ColumnNames+' FROM Table1 LEFT Join Table2 ON Table1.ID = Table2.ID'
Name exists in both the tables, but lets say table two has less matching records. So I always want to get Name from Table1.
In anyway can we set a preference on one particular table using any inbuilt clause.
Simply prepend the columns with the true table name, like this:
SET #SQLStmt = 'SELECT Table1.'+REPLACE(#ColumnNames,',',',Table1.')+' FROM Table1 LEFT Join Table2 ON Table1.ID = Table2.ID'
This should turn your string of Id,Name,Salary into Table1.Id,Table1.Name,Table1.Salary

How to INSERT INTO table column with string/variable

This is the data I have pulled from powershell and inserted it into a #temptable:
Name : SULESRKMA
Location : Leisure Services - Technology Services
Shared : False
ShareName :
JobCountSinceLastReset : 0
PrinterState : 131072
Status : Degraded
Network : False
I'm while looping through the data and have stripped the values from the identifiers. I'd like to use these identifiers to insert the values into a table with identical Column names to the identifiers. So for example, I have a variable called #identifier = "Name" and a temp table #printers with a column name of Name. I'd like to do something like:
SELECT --select statement
INSERT INTO #printers(#identifier)
But This doesn't seem to work, unsurprisingly. Is there a way to accomplish this? (The #identifier variable will be changing to the other identifiers in the data throughout the course of the while loop.)
Any alternate suggestions that don't even involve using this sort of method are welcome. My ultimate goal is just to get this data as a row into a table.
(I'm currently using Microsoft SQL Server Management Studio if that matters)
First, it's unlikely you need to loop over anything in this situation. Think set based operations when you think about SQL.
INSERT INTO #temptable (Column1Name, Column2Name, Column3Name)
VALUES (#identifer, #anotherIdentifier, #someOtherIdentifier)
--optional clauses
WHERE Column1Name = 'some value' OR Column1Name = #someIdentifier
Or you can SELECT INTO
SELECT
#identifier,
#anotherIdentifer,
#someOtherIdentifier
INTO #temptable
It's important that you have a value in your SELECT INTO for each column in the table which you are trying to add the data to. So, for example, if there were 4 columns in #temptable and you only had 3 values to insert (columns 1, 2 , and 3) then you'd need to NULL column 4 or set it statically.
SELECT
#identifier,
#anotherIdentifer,
#someOtherIdentifier,
NULL
INTO #temptable
--or
SELECT
#identifier,
#anotherIdentifer,
#someOtherIdentifier,
'static value'
INTO #temptable
EDIT
If you want to use a varible to speciy the column that you want to insert into, you have to use dynamic sql. Here is an example:
if object_id ('tempdb..#tempTable') is not null drop table #tempTable
create table #tempTable (Column1Name int, Column2Name int, Column3Name int)
declare #columnName varchar(64) = 'Column1Name'
declare #sql varchar(max)
set #sql =
'insert into #tempTable (' + #columnName + ')
select 1'
exec(#sql)
select * from #tempTable

SQL Single Value or All

For report purposes in SSRS I need an SQL query for one parameter which will select only one value or all values (not two or more). It's a single value parameter.
Well, my query should looks like this, but it didn't work:
SELECT ft.id, ft.name
FROM fundtable ft
UNION ALL
SELECT '11111111-1111-1111-1111-111111111111','All'
DECLARE #funds NVARCHAR(MAX)
SELECT #funds = COALESCE(CAST(entity_id AS NVARCHAR(255)),',')
FROM epev_conduit
SELECT #funds
If you are using this query for a dataset that your parameter is using for the Available Values, you don't need to put in into a string. Just use:
select ft.id, ft.name
from fundtable ft
union all
Select '11111111-1111-1111-1111-111111111111','All'
The use your Name field for the Label and your ID for the Value. You can Specify a Default value expression of
="11111111-1111-1111-1111-111111111111"
if you want the default to be all.
This should do the trick.
SELECT *
FROM dbo.YourTable
WHERE #id = id
OR #id = '11111111-1111-1111-1111-111111111111'

Resources