Inserting Replace Function into Query - sql

I found this solution which I'm pretty sure will do exactly what I'm trying to accomplish, unfortunately, all my SQL is self-taught and I can't figure out how to integrate the solution into the query I'm working with.
I tried putting everything above the SELECT statement, but I couldn't set the #testString variable to the COND_NOTE.TEXT field, which makes sense, since all of that happens inside the main query select.
Apologies for essentially asking someone to give me a crash course in presumably a pretty basic application of SQL syntax.
SELECT
CASE WHEN DM_IAM_D_I_ROOT.ZZCAP_FACILITY = 'N200' THEN 'MT'
WHEN DM_IAM_D_I_ROOT.ZZCAP_FACILITY = 'N202' THEN 'PI'
WHEN DM_IAM_D_I_ROOT.ZZCAP_FACILITY = 'N204' THEN 'FL'
ELSE 'Err' END AS FAC
,right(DM_IAM_D_I_ROOT.ISSUE_ID,12) AS ISS_ID
--The following line is the one that I want to use the solution from the referenced question in.
,REPLACE(REPLACE(COND_NOTE.TEXT, '"', '"'), 'br/>', '') NOTES
,COND_NOTE.LINE_COUNTER
FROM
DM_IAM_D_I_ROOT
LEFT JOIN
(
SELECT
DM_BOBF_D_TXCROOT.HOST_KEY
,DM_BOBF_D_TXCROOT.MANDT
,DM_BOBF_D_TXCTXT.TEXT_TYPE
,DM_BOBF_D_TXCCON.LINE_COUNTER
,DM_BOBF_D_TXCCON.TEXT
FROM
DM_BOBF_D_TXCROOT
INNER JOIN DM_BOBF_D_TXCTXT
ON DM_BOBF_D_TXCROOT.DB_KEY = DM_BOBF_D_TXCTXT.PARENT_KEY AND DM_BOBF_D_TXCROOT.MANDT = DM_BOBF_D_TXCTXT.MANDT
INNER JOIN DM_BOBF_D_TXCCON
ON DM_BOBF_D_TXCTXT.DB_KEY = DM_BOBF_D_TXCCON.PARENT_KEY AND DM_BOBF_D_TXCTXT.MANDT = DM_BOBF_D_TXCCON.MANDT
WHERE
DM_BOBF_D_TXCROOT.MANDT = '100'
AND DM_BOBF_D_TXCTXT.TEXT_TYPE = 'ZCOND'
) COND_NOTE ON DM_IAM_D_I_ROOT.DB_KEY = COND_NOTE.HOST_KEY AND DM_IAM_D_I_ROOT.MANDT = COND_NOTE.MANDT
WHERE
DM_IAM_D_I_ROOT.ISSUE_TYPE = 'CAP'
AND DM_IAM_D_I_ROOT.MANDT = '100'
AND DM_IAM_D_I_ROOT.LCYCLE_CD NOT IN ('10', '64')
ORDER BY ZZCAP_FACILITY, ISSUE_ID, LINE_COUNTER

Related

Issue With SQL Pivot Function

I have a SQL query where I am trying to replace null results with zero. My code is producing an error
[1]: ORA-00923: FROM keyword not found where expected
I am using an Oracle Database.
Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From
(select s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no)
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
)
This expression:
nvl('Single-occupancy',0) as 'Single-occupancy',
is using an Oracle bespoke function to say: If the value of the string Single-occupancy' is not null then return the number 0.
That logic doesn't really make sense. The string value is never null. And, the return value is sometimes a string and sometimes a number. This should generate a type-conversion error, because the first value cannot be converted to a number.
I think you intend:
coalesce("Single-occupancy", 0) as "Single-occupancy",
The double quotes are used to quote identifiers, so this refers to the column called Single-occupancy.
All that said, fix your data model. Don't have identifiers that need to be quoted. You might not have control in the source data but you definitely have control within your query:
coalesce("Single-occupancy", 0) as Single_occupancy,
EDIT:
Just write the query using conditional aggregation and proper JOINs:
select s.service_sub_type_descr, ch.claim_id,
sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
table_" ci
on ch.claim_id = ci.claim_id join
table_3 s
on ci.service_type_id = s.service_type_id join
table_4 ppd
on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id;
Much simpler in my opinion.
for column aliases, you have to use double quotes !
don't use
as 'Single-occupancy'
but :
as "Single-occupancy",

How to give change working of having function dynamicaly on executing an sql statement?

I'm having a Sql code like as follows
Select a.ItemCode, a.ItemDesc
From fn_BOM_Material_Master('A', #AsOnDate, #RptDate, #BranchID, #CompID)a
Left Outer Join fn_INV_AsOnDate_Stock(#StockDate, #AsOnDate, #RptDate, #BranchID, #CompID, #Finyear)b
On a.ItemCode=b.ItemCode and b.WarehouseCode<>'WAP'
and a.BranchID=b.BranchID and a.CompID=b.COmpID
Where a.ItemNatureCode = 'F' and a.BranchID = #BranchID and a.CompID = #CompID
Group by a.ItemCode, a.ItemDesc
Having sum(b.CBQty)<=0
Here the problem is that im passing an "#ShowZeroStock" value as as bit if the "#ShowZeroStock" value is '1' then Having should not be validated or (i.e: All values from the table should be returned including zero)
So How to change the query based on passed bit value "#ShowZeroStock"
I can Use "If else " condition at the top and remove having in else part, but for a lengthy query i can't do the same.
Is this the logic you want?
Having sum(b.CBQty) <= 0 or #ShowZeroStock = 1

Trying to get better at understand sql queries

I'm a new developer in a corporate IT group. I feel completely lost looking at alot of the sql that's written in our code. There are many queries that are literally hundreds of lines long. Here's an example of a "smaller" one (the table/field names have been modified, but the structure is the same). Do I just suck at this or is it really difficult to understand? How would you approach rewriting it to be more manageable/understandable?
SELECT pd.commission_header_id COMMISSION_HEADER_ID
,pd.sales_rep_id DIRECT_SALESREP_ID
,pd.org_id ORG_ID
,LEAST(100, innview.spilt_percent) SPLIT_PCT
,pd.source SOURCE
,pd.application APPLICATION
,pd.plan PLANE
,pd.pay_freq pay_freq
,pd.emp_app_count EMP_APP_COUNT
,pd.client_name CLIENT_NAME
,pd.fed_id FED_ID
,pd.off_nbr OFF_NBR
,pd.payroll_num payroll_num
,TO_DATE(pd.product_start_date,'DD-MON-YY') PRODUCT_START_DATE
,pd.loss_date LOSS_DATE
,pd.acquisitions_ind ACQUISITIONS_IND
,pd.source_of_business SOURCE_OF_BUSINESS
,pd.prev_br_clt_nbr PREV_BR_CLT_NBR
,pd.previous_method PREVIOUS_METHOD
,pd.natl_acct_number NATL_ACCT_NUMBER
,pd.product_name PRODUCT_NAME
,pd.lost_reason LOST_REASON
,pd.client_id CLIENT_ID
,pd.lead_nbr LEAD_NBR
,pd.processed_date PROCESSED_DATE
,pd.rep_type REP_TYPE
,pd.order_number ORDER_NUMBER
,pd.conversion_type CONVERSION_TYPE
,SUBSTR(original_billing_info,1,INSTR(original_billing_info,'|',1,1)-1) BILLING_APPLICATION
,SUBSTR(original_billing_info,INSTR(original_billing_info,'|',1,1)+1,INSTR(original_billing_info,'|',1,2)-INSTR(original_billing_info,'|',1,1)-1) BILLING_CODE
,SUBSTR(original_billing_info,INSTR(original_billing_info,'|',1,2)+1,INSTR(original_billing_info,'|',1,3)-INSTR(original_billing_info,'|',1,2)-1) BILLING_PROD_GRP_NM
,SUBSTR(original_billing_info,INSTR(original_billing_info,'|',1,3)+1) BILLING_FIELD_FOR_CHRGS
,SUBSTR(original_discount_info,1,INSTR(original_discount_info,'|',1,1)-1) DISCOUNT_APPLICATION
,SUBSTR(original_discount_info,INSTR(original_discount_info,'|',1,1)+1,INSTR(original_discount_info,'|',1,2)-INSTR(original_discount_info,'|',1,1)-1) DISCOUNT_CODE
,CASE WHEN (NVL(innview.trans,0)) = 0
THEN 0
ELSE ( NVL(innview.comm,0)) / ( NVL(innview.trans,0))
END ORIGINAL_COMM_PCT
,pd.record_type RECORD_TYPE
,innview.trans PAR_SUM
,NVL(ocp.oic_clients_pk, pxmis.oic_client_products_pk_seq.nextval) CLIENT_PRODUCT_ID
,pd.associated_with ASSOCIATED_WITH_ID
,pd.refferal_sale refferal_sale
,pd.parent_client_nbr PARENT_CLIENT_NBR
FROM pxmis.pd_commissions pd
JOIN pxmis.oic_lookback_months olm ON (pd.application = olm.application
AND pd.plan = olm.plan)
LEFT OUTER JOIN pxmis.oic_client_products ocp ON (pd.off_nbr = ocp.off_nbr
AND pd.payroll_num = ocp.payroll_num
AND pd.application = ocp.application
AND pd.plan = ocp.plan
AND pd.sales_rep_id = ocp.direct_salesrep_id
AND pd.source = ocp.source
AND ocp.record_type in (:1,:2)
AND NVL(pd.refferal_sale,'NON REF') = NVL(ocp.refferal_sale,'NON REF'))
JOIN (SELECT SUM(NVL(transaction_amount,0)) as trans
,SUM(commission_amount) as comm
,SUM(pd2.oic_split_percent) as spilt_percent
,pd2.application as application
,pd2.plan as code
,pd2.sales_rep_id as sales_rep_id
,pd2.payroll_num as client_nbr
,LPAD(pd2.off_nbr,4,0) as off_nbr
FROM pxmis.pd_commissions pd2
JOIN pxmis.oic_lookback_months olm2 ON (pd2.application = olm2.application
AND pd2.plan = olm2.plan)
WHERE CASE WHEN (pd2.record_type IN ('SAPBA','ASAPBA'))
THEN pd2.SUB_RECORD_TYPE
ELSE 'Eligible'
END = 'Eligible'
AND pd2.record_type IN ('SDBDA', 'ASDBDA',
decode(:3,'CHCST','SAPBA',NULL),
decode(:4,'CHCST','ASAPBA',NULL),
'SAPBP','ASAPBP')
AND pd2.processed_date BETWEEN ADD_MONTHS(:5,(olm2.lookback_months_high - 1) * -1) AND ADD_MONTHS(:6, (olm2.lookback_months_low - 2) * -1) - 1
and :7 between olm2.effective_start_date and olm2.effective_end_date
and olm2.function_type = :8
GROUP BY pd2.application
,pd2.plan
,pd2.sales_rep_id
,pd2.payroll_num
,LPAD(pd2.off_nbr,4,0)) innview on (innview.application = pd.application
AND innview.code = pd.plan
AND innview.sales_rep_id = pd.sales_rep_id
AND innview.client_nbr = pd.payroll_num
AND innview.off_nbr = LPAD(pd.off_nbr,4,0))
WHERE :9 BETWEEN olm.effective_start_date AND olm.effective_end_date
AND pd.sales_rep_id <> -3
AND pd.record_type IN ('SAPBP','ASAPBP')
AND NOT EXISTS(SELECT 'X'
FROM pxmis.pd_commissions pd3
WHERE pd3.application = pd.application
AND pd3.plan = pd.plan
AND pd3.sales_rep_id = pd.sales_rep_id
AND pd3.payroll_num = pd.payroll_num
AND (pd3.record_type in ('CHCST','ACHCST')
or ( pd3.record_type = 'SAPBA'
and pd3.sub_record_type = 'Chargeback')))
AND pd.commission_header_id = (SELECT MAX(pd4.commission_header_id)
FROM pxmis.pd_commissions pd4
WHERE pd4.application = pd.application
AND pd4.plan = pd.plan
AND pd4.sales_rep_id = pd.sales_rep_id
AND pd4.payroll_num = pd.payroll_num
AND pd4.record_type = pd.record_type)
AND olm.function_type = :10
AND pd.processed_date BETWEEN ADD_MONTHS(:11,(olm.lookback_months_high - 1) * -1) AND ADD_MONTHS(:12, (olm.lookback_months_low - 2) * -1) - 1
AND pd.source = :13
AND pay_freq IS NOT NULL
AND pd.core_conversion_revenue IS NULL;
Sidenote: (Due to my reputation I can not make comments:)
This is my first time answering. Hopefully it will help.
I do not know if it might help, but most of the SQL script (maybe all of it), can be rewritten in other languages. For example you can use JOINS in C# .NET LINQ.
But a way I usually separate the SQL script, is to look for the keywords and see what they do. Do not confuse the big letters from the small ones.
The SELECT function selects all of the datas.
The TO_DATE function says that it will convert the a string to date (source: http://www.techonthenet.com/oracle/functions/to_date.php)
The LEAST function returns the smallest number between the variables you have as parameters (Source: http://www.techonthenet.com/oracle/functions/least.php)
You can do this for every function, and try and grasp what the script does.
I think you could end the script here: FROM pxmis.pd_commissions pd
Also I have seen that you do a JOIN.
Here you could properly make a new script and run that code.
Right now I might not be able to make it more readable. (Mostly because I work with .NET C# linqs).
Again hopefully it helped in some way.

Use Case Statement in Join

Hi every one i want to use case statement in join using this query and got error
Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID
FROM F_SALESINVOICEITEM SII
INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID
INNER JOIN #TempTableSearch ts ON CASE
WHEN ts.ACCOUNTTYPE = '1' THEN ts.ACCOUNTID=SI.TENANCYID
WHEN ts.ACCOUNTTYPE='2' THEN ts.ACCOUNTID=SI.EMPLOYEEID
WHEN ts.ACCOUNTTYPE='3' THEN ts.ACCOUNTID=SI.SUPPLIERID
WHEN ts.ACCOUNTTYPE='4' THEN ts.ACCOUNTID=SI.SALESCUSTOMERID
Error
Incorrect syntax near '='.
Please help me to solve this error.
IT should be,
ON
ts.ACCOUNTID = CASE
WHEN ts.ACCOUNTTYPE = '1' THEN SI.TENANCYID
WHEN ts.ACCOUNTTYPE = '2' THEN SI.EMPLOYEEID
WHEN ts.ACCOUNTTYPE = '3' THEN SI.SUPPLIERID
WHEN ts.ACCOUNTTYPE = '4' THEN SI.SALESCUSTOMERID
END
Instead of using CASE, I'd much rather do this:
Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID
FROM F_SALESINVOICEITEM SII
INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID
INNER JOIN #TempTableSearch ts ON
(ts.ACCOUNTTYPE='1' AND ts.ACCOUNTID=SI.TENANCYID)
OR (ts.ACCOUNTTYPE='2' AND ts.ACCOUNTID=SI.EMPLOYEEID)
OR (ts.ACCOUNTTYPE='3' AND ts.ACCOUNTID=SI.SUPPLIERID)
OR (ts.ACCOUNTTYPE='4' AND ts.ACCOUNTID=SI.SALESCUSTOMERID)
To explain why the query didn't work for you: the syntax of the CASE requires an END at the end of the clause. It would work, as the other solutions proposed suggest, but I find this version to be more convenient to understand - although this part is highly subjective.
you can do this, so you have no chance to misspell something (note that ACCOUNTTYPE and ACCOUNTID used only when needed, you don't have to copy-paste it)
select
convert(varchar(10), SII.SIDATE,103) as DATE,
SII.SALEID, SII.ItemName, SI.TenancyID
from F_SALESINVOICEITEM as SII
inner join F_SALESINVOICE as SI on SI.SALEID = SII.SALEID
outer apply (
'1', SI.TENANCYID
'2', SI.EMPLOYEEID
'3', SI.SUPPLIERID
'4', SI.SALESCUSTOMERID
) as C(ACCOUNTTYPE, ACCOUNTID)
inner join #TempTableSearch as ts on
ts.ACCOUNTTYPE = C.ACCOUNTTYPE and ts.ACCOUNTID = C.ACCOUNTID
You have syntax error. You are missing END there.
You must understand that CASE ... END block is NOT equivalent to IF { } from C-like languages. Much rather this is equivalent to elaborate version of ... ? ... : ... operator from C-like languages. What it means that the WHOLE CASE block must essentially evaluate to single value and that this value has to be the same type no matter which case of the block is executed. This means that:
CASE
WHEN ts.ACCOUNTTYPE = '1' THEN ts.ACCOUNTID=SI.TENANCYID ...
END
Is fundamentally incorrect unless you work on a version of database that will allow you bool value as a value (SQL Server won't allow it for example but I think some of MySQL version used to allow it - not sure about this). You probably should write something like:
CASE
WHEN ts.ACCOUNTTYPE = '1' AND ts.ACCOUNTID=SI.TENANCYID THEN 1
WHEN ts.ACCOUNTTYPE='2' AND ts.ACCOUNTID=SI.EMPLOYEEID THEN 1
WHEN ts.ACCOUNTTYPE='3' AND ts.ACCOUNTID=SI.SUPPLIERID THEN 1
WHEN ts.ACCOUNTTYPE='4' AND ts.ACCOUNTID=SI.SALESCUSTOMERID THEN 1
ELSE 0
END = 1
Notice how the whole CASE block evaluates to 1 or 0 and then it is compared to 1. Of course instead of 4 WHEN's you could use one WHEN with combination of AND's, OR's and ( ) brackets. Of course in this particular case answer by #ppeterka 66 is correct as CASE is not suited for what you really wanted to do - I'm just trying to clarify what CASE really is.

T-SQL - Aliasing using "=" versus "as" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Is there any particular reason (performance or otherwise) to use AS ahead of = when aliasing a column?
My current approach (for readability) is to use this:
select
alias1 = somecolumn
alias2 = anothercolumn
from
tables
etc...
instead of this:
select
somecolumn as alias1
anothercolumn as alias2
from
tables
etc...
Is there a performance or maintainability reason to use one over the other?
‘=’ isn't valid ANSI SQL, so you'll have difficulty should you wish to run your application on a different DBMS.
(It's when ANSI form is used but the optional ‘AS’ is omitted I find the results difficult to read, personally.)
To put in some counterweight, I prefer using =.
If I am the consumer of the query results in some way, I find it more convenient to see what columns I as a consumer can use.
I prefer this
SELECT
[ElementObligationID] = #MaxElementObligationID + eo.ElementObligationID
, [ElementID] = eo.ElementID
, [IsotopeID] = eo.IsotopeID
, [ObligationID] = eo.ObligationID
, [ElementWeight] = eo.ElementWeight * -1
, [FissileWeight] = eo.FissileWeight * -1
, [Items] = eo.Items * -1
, [Comment] = eo.Comment
, [AdditionalComment] = eo.AdditionalComment
, [Aanmaak_userid] = #UserID
, [Aanmaak_tijdstip] = GetDate()
, [Laatste_wijziging_userid] = #UserID
, [Laatste_wijziging_tijdstip] = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
over this
SELECT
#MaxElementObligationID + eo.ElementObligationID AS [ElementObligationID]
, eo.ElementID AS [ElementID]
, eo.IsotopeID AS [IsotopeID]
, eo.ObligationID AS [ObligationID]
, eo.ElementWeight * -1 AS [ElementWeight]
, eo.FissileWeight * -1 AS [FissileWeight]
, eo.Items * -1 AS [Items]
, eo.Comment AS [Comment]
, eo.AdditionalComment AS [AdditionalComment]
, #UserID AS [Aanmaak_userid]
, GetDate() AS [Aanmaak_tijdstip]
, #UserID AS [Laatste_wijziging_userid]
, GetDate() AS [Laatste_wijziging_tijdstip]
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
just my 2c.
I wouldn't use it simply as it looks far too much like equality operation. 'AS' is clear inasmuch that it's not ambiguous to me.
Its the same as not using upper case in sql, I find it harder to read.
I'm not as lucky as others who have posted here. The code I work with is usually written by someone else and it is rare that there are not CASE statements or other calculations, concatenations or logic that cause a single entry to span over several rows of T_SQL script.
Using a equal sign instead of 'AS' is by far easier to read. With an equal sign you know the alias name you are looking for is in the first position of the row. When 'AS' is used and the T_SQL spans multiple lines, the alias name could literally be anywhere.
It is far, far, far easier to find the 'Items' alias when equals is used than when 'AS' is used.
SELECT
ElementObligationID = #MaxElementObligationID + eo.ElementObligationID
, ElementID = eo.ElementID
, IsotopeID = eo.IsotopeID
, ObligationID = eo.ObligationID
, ElementWeight = eo.ElementWeight * -1
, FissileWeight = eo.FissileWeight * -1
, Items = CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END
, Comment = eo.Comment
, AdditionalComment = eo.AdditionalComment
, Aanmaak_userid = #UserID
, Aanmaak_tijdstip = GetDate()
, Laatste_wijziging_userid = #UserID
, Laatste_wijziging_tijdstip = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
Now imagine having more than 5 times the amount of code that is here and needing to find the 'Items' alias.
SELECT
#MaxElementObligationID + eo.ElementObligationID AS ElementObligationID
, eo.ElementID AS ElementID
, eo.IsotopeID AS IsotopeID
, eo.ObligationID AS ObligationID
, eo.ElementWeight * -1 AS ElementWeight
, eo.FissileWeight * -1 AS FissileWeight
, CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END AS Items
, eo.Comment AS Comment
, eo.AdditionalComment AS AdditionalComment
, #UserID AS Aanmaak_userid
, GetDate() AS Aanmaak_tijdstip
, #UserID AS Laatste_wijziging_userid
, GetDate() AS Laatste_wijziging_tijdstip
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
'AS' vs '=' is not a capricious and arbitrary preference. I am not exaggerating when I say there have been times when it would take several minutes to find the alias name I am looking for because the author of the script I am now in charge of maintaining did not use the equals sign with their alias. I cannot think of a bigger waste of time, money and resources than paying an IT professional to look for alias names in code!! There is a right and wrong answer if you care about maintainability, readability, and efficiency. Your job is to provide business value, not to spend your day looking for Waldo!
"=" is just plain ambiguous.
If you indent to break out each select clause...
select
alias1 = somecolumn,
alias2 = anothercolumn,
result = column1 * column2
from
table
....
select
somecolumn as alias1,
anothercolumn as alias2,
column1 * column2 as result
from
tables
...
= can be confused with assignment and equality; actually, the form I really don't like is when it looks like a string (usually when spaces are involved):
somecolumn as 'alias 1'
or
'alias 1' = somecolumn
I far prefer the alternative notation:
somecolumn as [alias 1]
The postfix alias form (with or without the "AS") is consistent between column and table aliases. Personally, I'd like an option to enforce the use of "AS", and then you wouldn't have the situation:
select
columnA,
columnB
columnC
from
table
producing a result set with two columns instead of the expected 3.
I'd also say that with the prefix "=" form, it can make it more difficult to read if you're mixing obtaining a result set and variable assignment:
select
cA = columnA,
#cB = columnB,
cC = columnC
from
table
The three ways I know of to alias:
TableColumn AS MyAlias
TableColumn MyAlias
MyAlias = TableColumn
Re: 1), I prefer this as it is the most self-documenting code (IMO), and it lets me search for AS if I need to find aliases..
Re: 2), This is my second choice, but without the AS, I am never sure whether this is a cut-and-paste error or not, especially in long, badly-formatted queries.
Re: 3), I don't like this because a) it looks like an assignment, and b) it blends in too much with ON clauses and CASE statements
So, my vote is to use the AS keyword for your aliases.
I prefer using AS since = is used in the where statement, and can be confusing in a long query.
I prefer using neither of those. I just give the name of the column without any keyword in between
SELECT MAX(price_column) maximumprice FROM prices
Column aliases declared by "=" syntax are deprecated in SQL Server 2008 and not supported in the next version. See MSDN article.
While I have a preference for using AS, the really key thing here is to have a corporate standard and to follow it. If more of your people use AS than = then everyone should use it. Coding standards are what makes it easier to maintain code not the particular standard you pick. If everyone uses the same thing, then your eye gets used to picking it out.
I like the
SELECT
column1 = table.column1
,column2 = table.colum2
FROM table
I find AS not as easily noticable compared to a = sign (I can spot = quicker than AS)
Also when one just does SELECT column alias, sometimes it's confusing to know which one is which :)
Since I write SQL for several different relational database management systems, I prefer to use a syntax which works on all of them, which normally means writing ANSI compatible SQL. My normal formatting preference is:
SELECT
S.name AS SchemaName,
O.name AS ObjectName,
C.column_id AS ColumnId,
C.name AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
As an alternative formatting of the above, the following makes it easier to see the column alias names:
SELECT
S.name
AS SchemaName,
O.name
AS ObjectName,
C.column_id
AS ColumnId,
C.name
AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
**even i prefer using 'as' instead of '=' . '=' makes confusion in code.
e.g :
column as alias1
You don't have to use either
Drop the AS and use
SELECT originalname alias
FROM
tablename