sql preferred selection type? [duplicate] - sql-server

This question already has answers here:
Different ways to alias a column
(3 answers)
Closed 8 years ago.
SELECT a=1,b=2
vs
SELECT 1 AS a, 2 AS b
what approach should i use ? (by best practice decisions)
Is there any advantages of one vs the other ?

Personally I use AS - it is more explicit and used elsewhere (table aliases).
It is also standard - using the = syntax will not work on some databases.
I don't believe there are any performance implications for using one over the other.

I dont think where is a difference. But i would prefer the second approach. I think its more logical than the first.
So, i use the AS approach.
AS temporarily assigns a table column a new name. This grants the SQL developer the ability to make adjustments to the presentation of query results and allow the developer to label results more accurately without permanently renaming table columns. Source

I use AS. It's a more SQL friendly way!

SELECT 1 AS a, 2 AS b
is common for all DBs

Related

How to avoid SQL Server error on ORDER BY with duplicate columns

Although this question references PHP, it is not actually PHP-specific, so I have not flagged it as such.
We have a PHP framework which supports multiple DB back-ends.
There is a generic function in our data object class, which allows you to get records from the underlying table, with a specified criteria and sort order.
It looks something like this:
function GetAll($Criteria, $OrderBy = "") {
...
// Add primary key (column 1) to end of order by list,
// so that returned order is predictable.
if ($OrderBy != "") {
$OrderBy .= ", ";
}
$OrderBy .= "1";
...
// Build and run query, returning the result as an array.
}
If you specify an $OrderBy argument of StaffID on a Staff object, the resulting SQL looks something like the following:
SELECT * FROM adminStaff ORDER BY StaffID, 1;
This works fine on a MySQL back-end, and from my searching of the web it should also be fine on most other DB back-ends. However, when using SQL Server, we get the following error message:
A column has been specified more than once in the order by list.
Columns in the order by list must be unique.
This arises because SQL Server disallows the same column appearing multiple times in the ORDER BY clause. In this case StaffID is column 1 and therefore we have multiple instances of the same column.
Is there a way to disable this check in SQL Server? MySQL provides a lot of options to enable/disable strictness checks and incompatible features - does SQL Server provide anything of that nature that would allow the above query to run without errors?
If not, do you have any suggestions for how we could resolve this in our data-object layer? Bear in mind we need to maintain compatibility with existing projects which expect this behaviour, so it is not sufficient to only include the first column when $OrderBy is blank.
The situation is also slightly complicated in the fact that the field list is customisable elsewhere in the data object configuration, so we can't rely on * being used as the field list - it could contain pretty much anything that is valid in a normal SQL field list. However, if that is asking too much, a solution to the simpler case (as outlined above) would be a good start!
In SQL Server you are able to sort either by column name or by ordinal position of the column order in the SELECT list.
In your case the column StaffID became the ordinal position 1. Hence SQL Server cannot sort the same result set based on the same column twice.
If you remove the 1 from your query, the problem will be solved.
Avoid using the ordinal position of the column for sorting.
The basic question - is it possible to suppress this SQL Server restriction on ORDER BY column duplication - was answered by Venu: No it is not.
There are various suggestions (mostly from me) about how you could possibly code around this limitation in a generic manner. For any future readers, those answers are probably the most helpful if you are adapting an existing system. (If you are starting from scratch, just try and avoid this situation altogether.)
However, the actual solution that I came to was to add versioning to our internal API for our DBAL. The API version is now 2 but you can call setApiVersion(1) to instruct the back-end to use the old version of the API instead.
v2 is identical to v1* except it no longer automatically adds column 1 to the ORDER BY unless it is completely blank. Therefore, the SQL Server issue is resolved for new (v2) projects, whilst existing projects can be set to use the v1 API and therefore continue to work correctly (but without SQL server compatibility).
(* Actually, I've taken this opportunity to make some other breaking changes in v2, but that is not relevant to this answer.)
I've come up with a couple of potential solutions at the framework level. All of them have performance implications which would need to be profiled, and in practice that may rule some or all of them out. However, in theory at least, these are ways that a generic solution could be implemented.
Omit the ORDER BY altogether, and do the sorting in code. Would involve parsing the provided ORDER BY string. Would be problematic if ORDER BY contained expressions, but I can't remember ever seeing that in our projects, so can probably be ignored. Probably the slowest solution.
Perform the query without the ORDER BY, limiting the results set to a single row. Use resulting column list to work out whether column 1 is already in the ORDER BY clause, and therefore whether to add it. Then run the full query. Would require parsing the provided ORDER BY string. Query caching may mean this won't add as much overhead as it appears.
Parse the field list to get the first column name and see if this appears in the ORDER BY clause. If field list contains * or table.* would require a schema lookup. May be too difficult if we need to deal with table aliases and wildcards in combination.
Parse ORDER BY string and see if it contains any primary key. If so it is already uniquely ordered and doesn't require the addition of an extra field. Would require a schema look-up.
Use a sub-select to give us a new instance of the column that we can sort on instead. Not sure whether SQL Server would still complain that this is the 'same' column, though.
Could you just append '--' to your OrderBy parameter when working with SQL Server and just explicitly define the Order By fields where necessary?

Searching an MS SQL database for a specific word [duplicate]

This question already has answers here:
Search for a string in all tables, rows and columns of a DB
(15 answers)
Closed 9 years ago.
I've been scouring online for an example of how to do this but haven't found anything at all. All the queries I've found assume you know what table you want to search.
I'm looking for a SQL query to simply search the ENTIRE database for a specific word.
There has to be such a thing right?
This is for MS SQL 2005/2008
Thanks
What do you mean by "entire database"? You need to find your values in tables only, or in object definitions, too?
I assume the former. In this case, you don't have to really know the structure of your DB. Try those views below. With them, you can construct your select queries on all the tables / colums. Just filter out non-*char columns, views and system tables, and you're ready to go - you can "automatically" generate multiple select statements.
select top 100 * from information_schema.tables
select top 100 * from information_schema.columns
The other option, is to use some addon to SSMS, like this one:
http://www.ssmstoolspack.com/
It has an option to search entire database.
But be advised, that both solutions will have a great impact on performance of your server.

SQL Script to know where the data is located [duplicate]

This question already has answers here:
Find a value anywhere in a database
(18 answers)
Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement
(21 answers)
Search all tables, all columns for a specific value SQL Server [duplicate]
(4 answers)
Closed 8 years ago.
My question might sound stupid, but does there exist a script that could find out where in database, for which tables, is the desired data located? Say for example, i need to found where Texas is located in database, in which tables and in which column.
There exists a script that could find out the tables, SP, views based on the column name provided. Is there any script that could find out tables, column name etc based on the actual data?
Hope the question is understood.
Best Regards
Josh Walker has a script that will find the number of incidences a string of text is found, and in which tables:
http://www.sqlservercentral.com/scripts/Miscellaneous/65769/
And, this statement should find any procedure code that contains the text you are looking for:
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%whatever%'
The SSMS Tools Pack gives you this kind of search functionality plus various other cool things for free. And no, I don't work for them!
I have got one great tool that can find data anywhere located in the database. It is known as SQL Locator. Just Google it, that should be easy to find. Plus it is a freeware to download.
Thanks!

Enumerated types in SQL Server 2008?

Is there some kind of mechanism in SQL Server to allow Enumerated type like functionality?
For example, if I have a column Called "UpdateStatus" it usually gets setup with single letter values like so:
D
X
U
I
This could equate to a lot of things. That leads to confusion. The alternative is to have it be a string column like this:
Downloaded
Deleted
Updated
Initialized
But that has its own problems. Eventually someone is going to write something like this: where UpdateStatus = 'Initalized' (spelled wrong). Plus I hear that keying off of strings is not all that performant.
So, is there any kind of enumerated type for SQL Server that can help out with this? Basically I am looking for compile time checking that a value being compared (ie "Initialized") is part of a list of values.
I am using SQL Server 2008.
Why not have lookup table that contains the code and description. Creating a foreign key to this lookup table will result in only valid codes being used.
Besides lookup tables (FKs), in simple cases, you can use check constraints:
CREATE TABLE my_table (
UpdateStatus VARCHAR2(11)
CHECK( UpdateStatus IN ('Downloaded', 'Deleted', 'Updated', 'Initialized'))
)
The only way that I've seen this done is by using a UDF to evaluate whether or not the enum's string representation is valid. It's slow, it's painful, and usually not worth it, but at least you have a way to fail loudly instead of silently.
And remember, you can't RAISERROR in a UDF so you have to cause an intentially cause an error, and log separately.
Ultimately, at the moment, the 'perfect' solution to the problem would be to approach from the other side -- you can achieve this mentality with a code-first ORMs, which would allow you to use native enums in your code, and the corresponding SQL lookups will be created properly in migration.
Here's to hoping we get enums soon, we're feeling a little left out.

Passing an array of values to a stored procedure in SQL 2005 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
T-SQL stored procedure that accepts multiple Id values
Does T-SQL accomodate for array values as parameters for stored procedures? If so how can this be achieved.
T-SQL dialect in SQL Server 2005 does not support neither arrays, nor anything similar, so they have to be emulated. SQL Server 2008, however, supports table-valued parameters, which can be used as arrays.
What I prefer to use instead is a comma (or other special character) separated list which I will split/explode first thing in my sproc. This will then give me a table of values to work with and that I can then join on or perform other actions on later on in my stored procedures.
You can also look into passing in table parameters, but I kind of like my way more just as a personal preference.
It was often achieved passing in a CSV, which is obviously limited. With SQL 2005 an Xml parameter may be much better suited, with a serializer suited to your needs perhaps.
There may be more and I'll come back if I think of any.
There are no arrays in sqlserver. However, What are you trying to do? What would the values as parameters be used for? You can send sql an "array" but the sp would have to be dynamic.

Resources