SQL AS statement without column name shortcut - sql

what does the AS in a statement such as below do?
SELECT column AS
FROM table
Since there is no shortcut, does it even do anything?

You did not tag your actual RDBMS, the following is valid for SQL-Server, but you'll be able to transfer this to your system:
--A dummy table as declared table variable
DECLARE #DummyTbl TABLE(SomeColumn INT);
INSERT INTO #DummyTbl VALUES(1),(2),(3);
--Variation of namings
SELECT SomeColumn --The orginal name
,SomeColumn AS OtherName --A classical alias
,SomeColumn test --The alias does NOT need the 'AS'
,SomeColumn [AS] --You may name your output 'AS'
FROM #DummyTbl;
But your syntax is - at least with SQL Server - not valid. AS is - in this context - a reserved word.

Related

String_Split inserts only the first value

I'm trying to insert comma separated Guids into a temp table, to later check for a value using IN in these Guids. The following query is inserting only the first value in the table twice.
DECLARE #campaignids nvarchar(max) = '1DEBD122-FF1B-4E87-8812-D427ABA5D54E,FBD06A2E-24D1-4C06-B71D-B4306D8EA3BD'
DECLARE #TempCampaignIds TABLE (CampaignId uniqueidentifier)
INSERT INTO #TempCampaignIds
SELECT CAST(#campaignids AS uniqueidentifier)
FROM STRING_SPLIT(#campaignids, ',')
SELECT CampaignId FROM #TempCampaignIds
--result
CampaignId
1DEBD122-FF1B-4E87-8812-D427ABA5D54E
1DEBD122-FF1B-4E87-8812-D427ABA5D54E
You need to use the value from the string:
INSERT INTO #TempCampaignIds (CampaignId)
SELECT CAST(s.value AS uniqueidentifier)
FROM STRING_SPLIT(#campaignids, ',') s;
Here is a db<>fiddle.
I'm actually surprised that your code works, but SQL Server converts the first value of such a string without an error. That doesn't seem to happen for other data types. In fact, SQL Server appears to look at only the first 36 characters for a unique identifier.

How to column schema of arbitrary query in SQL server

I want to get just schema of arbitrary sql query in SQL server.
For example-
Create Table Tabl1(Ta1bID int ,col1 varchar(10))
Create Table Tabl2(Tab1ID int ,col2 varchar(20))
SQL Query -
SELECT col1, col2
FROM Tab1
INNER JOIN Tab2 ON Tab1ID = Tab2ID
Here result will have this schema-
Col1 varchar(10), Col2 varchar(20)
I want to know what will be schema of result.
PS : I have just read access on the server where I am executing this query.
Any way to do this?
The schema, you mean to say datatype right? For resulted datatype will you always know when you operate on table(s). In your case both column is varchar datatype, so it will give character datatype, that you may convert into any character datatype like varchar, nvarchar, char, ntext etc.
Basic thing is, table designing was/is done by, so that time we know why we define datatype, now when you execute query below , you always know what will come with datatype of each column.
SELECT col1, col2
FROM Tab1
INNER JOIN Tab2 ON Tab1ID = Tab2ID
This though will issue when you use dynamic query, where you run time add column as per your requirement and you then execute which may or may not give error, due to mismatch of wrong datatype.
like
declare #sqlstring nvarchar(max)
set #sqlstring = 'declare #t table (name varchar(50))
insert into #t values(''Minh''),(''Tinh''),(''Justin'')
Select * from #t where Name like ''%in%'''
EXEC sp_executesql #sqlstring
I had similar problem before, but I had to create tables (70+) of each query one by one.
If there is a pattern, write a tool to generate create table
statement.
If not and it's one time job, just create them manually.
If it's not one time job, you might be thinking, why would store temp
date in table instead of temp table.

SELECT #local_variable=values from table where values can have multiple values

I am using below query
SELECT #local_variable=Adtid from table where Adtid can have multiple values stored into it. As I don't know what to use instead of '=' in #local_variable=Adtid. Can anyone suggest please what I should use instead of '=' so that my local varaible can have all values of Adtid
The variable can't actually hold multiple values. You can declare a table variable instead, where you can then do something like
declare #tableVariable table
(
Adtid int
);
insert into #tableVariable
select Adtid from table where Adtid ...
This puts the relevant rows inside your table variable. Now you can use the table variable to eg. create a cursor (to go row by row in the data - you can also do that on the original select if you only need to go through once) or use it in a join clause.
You can use below syntax for get the Adtid as comma separator in result
DECLARE #local_variable VARCHAR(100) =''
SELECT #local_variable += CAST(Adtid AS VARCHAR) + ',' FROM TABLE
PRINT #local_variable
and another way as per below answer.

Declaring a Temporary Variable in Oracle Database

i have worked previously with SQL Server and was able to learn how to create temporary variables and use them in SQL
i used to write something like this:
declare #Student nvarchar(255)
select #Student = studentname from sometable where somecondition = 1
declare #teacher nvarchar(255)
select #teacher = teachername from sometable2 where somecondition >2
and then
select #student, #teacher, other columns from sometable where some condition
i want to do the same thing in ORACLE Database.
Please Help!
If you want to do this in SQL*Plus without using PL/SQL, you can use substitution variables:
column studentname new_value l_studentname
select studentname from sometable where somecondition = 1;
column teachername new_value l_teachername
select teachername from sometable2 where somecondition >2;
select '&l_studentname', '&l_teachername,' other columns
from sometable where somecondition;
The new_value clause in the column directive automatically assigns the value from any following select to a local variable, which I've prepended with l_ but you can call anything. You then reference that local variable in future queries with the & variable substitution syntax.
You can use them pretty much anywhere you'd normally have a value. e.g. in the where clause. Note that text values have to be enclosed in quotes, hence '&l_studentname'; without the quotes the value would be interpreted as a column name in this case, which wouldn't work.
You can declare a variable say
SOME_VAR VARCHAR2(255);
Then use it in your query directly
SELECT DISTINCT YT.TEACHER_NAME
INTO SOME_VAR
FROM YOUR_TABLE YT
WHERE YT.TEACHER_ID = 1;
Then you are free to use this variable, SOME_VAR, for further use
Of course, this will not work in a simple SQL statement, but in case you use it in a programming block, like a procedure.
Hope it helps

String manipulation SQL

I have a row of strings that are in the following format:
'Order was assigned to lastname,firsname'
I need to cut this string down into just the last and first name but it is always a different name for each record.
The 'Order was assigned to' part is always the same.......
Thanks
I am using SQL Server. It is multiple records with different names in each record.
In your specific case you can use something like:
SELECT SUBSTRING(str, 23) FROM table
However, this is not very scalable, should the format of your strings ever change.
If you are using an Oracle database, you would want to use SUBSTR instead.
Edit:
For databases where the third parameter is not optional, you could use SUBSTRING(str, 23, LEN(str))
Somebody would have to test to see if this is better or worse than subtraction, as in Martin Smith's solution but gives you the same result in the end.
In addition to the SUBSTRING methods, you could also use a REPLACE function. I don't know which would have better performance over millions of rows, although I suspect that it would be the SUBSTRING - especially if you were working with CHAR instead of VARCHAR.
SELECT REPLACE(my_column, 'Order was assigned to ', '')
For SQL Server
WITH testData AS
(
SELECT 'Order was assigned to lastname,firsname' as Col1 UNION ALL
SELECT 'Order was assigned to Bloggs, Jo' as Col1
)
SELECT SUBSTRING(Col1,23,LEN(Col1)-22) AS Name
from testData
Returns
Name
---------------------------------------
lastname,firsname
Bloggs, Jo
on MS SQL Server:
declare #str varchar(100) = 'Order was assigned to lastname,firsname'
declare #strLen1 int = DATALENGTH('Order was assigned to ')
declare #strLen2 int = len(#str)
select #strlen1, #strLen2, substring(#str,#strLen1,#strLen2),
RIGHT(#str, #strlen2-#strlen1)
I would require that a colon or some other delimiter be between the message and the name.
Then you could just search for the index of that character and know that anything after it was the data you need...
Example with format changing over time:
CREATE TABLE #Temp (OrderInfo NVARCHAR(MAX))
INSERT INTO #Temp VALUES ('Order was assigned to :Smith,Mary')
INSERT INTO #Temp VALUES ('Order was assigned to :Holmes,Larry')
INSERT INTO #Temp VALUES ('New Format over time :LootAt,Me')
SELECT SUBSTRING(OrderInfo, CHARINDEX(':',OrderInfo)+1, LEN(OrderInfo))
FROM #Temp
DROP TABLE #Temp