Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Tuesday, March 27, 2012

concat_ws() in mssql

hey folks, im busy trying to make my script compatible with different types of databases

so, for mysql i use the function 'concat_ws()' in my sql query
but.. this function is not valid if u use mssql

so my question is, does anyone now a function in mssql that does the same as concat_ws() in mysql?Originally posted by bertwasbeer
hey folks, im busy trying to make my script compatible with different types of databases

so, for mysql i use the function 'concat_ws()' in my sql query
but.. this function is not valid if u use mssql

so my question is, does anyone now a function in mssql that does the same as concat_ws() in mysql?

Good question ;)
My question for you: What does the concat_ws() in mysql? I've never saw mysql.|||CONCAT_WS(separator, str1, str2,...)

CONCAT_WS() stands for CONCAT With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator can be a string as well as the rest of the arguments. If the separator is NULL, the result will be NULL. The function will skip any NULL values after the separator argument. The separator will be added between the strings to be concatenated:

mysql> SELECT CONCAT_WS(",","First name","Second name","Last Name");
-> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(",","First name",NULL,"Last Name");
-> 'First name,Last Name'|||Originally posted by bertwasbeer
CONCAT_WS(separator, str1, str2,...)

CONCAT_WS() stands for CONCAT With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator can be a string as well as the rest of the arguments. If the separator is NULL, the result will be NULL. The function will skip any NULL values after the separator argument. The separator will be added between the strings to be concatenated:

mysql> SELECT CONCAT_WS(",","First name","Second name","Last Name");
-> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(",","First name",NULL,"Last Name");
-> 'First name,Last Name'

I've never heard about function like this in MSSQL, may somebody else has. Anyway you could create User-Defined Functions for sql2000.|||What do you want to do with it?
If you are concatenating a column from selected rows you can

declare @.s varchar(8000)

select @.s = coalesce(@.s + ',') + fld
from tbl
where col2 = 'test'

This will concatenate all the values into @.s separated by a comma.

Concat Null Yields Null Woes..

I have a bunch of views that concat fileds, some of which allow nulls
so I am using the isNull function when joining them. I dont want to
have to do this, I want to set the database so that concat null does
not yield null for all views and procedures.
How do I do this this in EM ?
I read and tried a bunch of stuff on this but nothings worked so far.
Please dont reply telling me to use the concat null yields null
setting - I think I know what needs doing - but I dont know "How" to do
it!
Thanks.Thats because QA uses ODBC connection and by default its set CONCAT....NULL
to ON. and it overrides the database setting that you might have given.
you will have to explicitely state it in the connection
SET CONCAT_NULL_YEILDS_NULL OFF.
And your view is just a query given a name. So it will take the connection
setting. There is no point in setting that flag during view creation. You
will have to set it during access.
Hope this helps.
--
-Omnibuzz (The SQL GC)
http://omnibuzz-sql.blogspot.com/|||You can set CONCAT_NULL_YIELDS_NULL at the database level with ALTER
DATABASE or at the server level using the 'user options' of sp_configure.
However, it is unlikely that this will provide the behavior you want because
OLE DB and ODBC APIs explicitly SET CONCAT_NULL_YIELDS_NULL ON when
connecting to provide ANSI standard compliance by default. SET
CONCAT_NULL_YIELDS_NULL OFF needs to be explicitly set by each OLEDB/ODBC
client application using the view.
The best approach to ensure consistent results is to specify ISNULL or
COALESCE in the view expression. One can also argue that concatenation is
better handled in the client application rather that the server side.
Note that CONCAT_NULL_YIELDS_NULL ON is required to take advantage of
features like indexes on computed columns and views.
Hope this helps.
Dan Guzman
SQL Server MVP
"hals_left" <cc900630@.ntu.ac.uk> wrote in message
news:1150110841.616205.127710@.c74g2000cwc.googlegroups.com...
>I have a bunch of views that concat fileds, some of which allow nulls
> so I am using the isNull function when joining them. I dont want to
> have to do this, I want to set the database so that concat null does
> not yield null for all views and procedures.
> How do I do this this in EM ?
> I read and tried a bunch of stuff on this but nothings worked so far.
> Please dont reply telling me to use the concat null yields null
> setting - I think I know what needs doing - but I dont know "How" to do
> it!
> Thanks.
>|||Thank you both.
Dan Guzman wrote:
> You can set CONCAT_NULL_YIELDS_NULL at the database level with ALTER
> DATABASE or at the server level using the 'user options' of sp_configure.
> However, it is unlikely that this will provide the behavior you want becau
se
> OLE DB and ODBC APIs explicitly SET CONCAT_NULL_YIELDS_NULL ON when
> connecting to provide ANSI standard compliance by default. SET
> CONCAT_NULL_YIELDS_NULL OFF needs to be explicitly set by each OLEDB/ODBC
> client application using the view.
> The best approach to ensure consistent results is to specify ISNULL or
> COALESCE in the view expression. One can also argue that concatenation is
> better handled in the client application rather that the server side.
> Note that CONCAT_NULL_YIELDS_NULL ON is required to take advantage of
> features like indexes on computed columns and views.
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "hals_left" <cc900630@.ntu.ac.uk> wrote in message
> news:1150110841.616205.127710@.c74g2000cwc.googlegroups.com...|||>> I have a bunch of views that concat fields [sic], some of which allow NULLs so
I am using the ISNULL() function when joining them. I dont want to have to
do this, I want to set the database so that concat NULL does not yield NUL
L for all views and pr
ocedures. <<
Oh, you want to write your own language and not bother with SQL! This
behavior is one of many reasons that columns are not anything like
fields and why I jump on newbies to actually read a book about the
language before they start coding.
Nobody should be so irresponsible as to give you that advice. Your
code would not port, would not work properly, etc. what needs doing
is a bit more education on your part instead of looking for kludges to
save yourself some typing. Also, why aren't you using QA or a code
editor instead of EM?
SQL programmers think of the schema as a whole. The first place to
look is the DDL and the Data Dictionary (which you probably do not
have, if you have that many NULLs). Which of these columns really
should be blanks, empty strings or other defaults and not NULL-able at
all? I will bet most of them, based on two decades of cleaning up
SQL.
You will find that most bad DML are kludges made in response to bad
DDL.|||And I thought the iea of newsgrouops was to help ....
Thanks for your advice, but with respect, this isnt the theory of
doing databases this is databases - real ones for real businesses with
real (small) budgets and real tight deadlines and working pretty well
considering ...

> Oh, you want to write your own language and not bother with SQL!
Not particularly, but yeah Im happy to break the rules now and then,
for good reasons of course, its worked so far nayway...
columns are not anything like fields
True, but that doesnt really get in the way of business, we focus on
the things that matter...

>why I jump on newbies to actually read a book about the language before they start
coding
Books suit some learning types, not mine, took the test, I know how I
learn best..
Also, why aren't you using QA or a code editor instead of EM?
EM is easier and faster (for me) to use.

>Data Dictionary (which you probably do not have, if you have that many NULLs).[/col
or]
Yeah I follow agile principles - My code is the documentation!
>Which of these columns really should be blanks, empty strings or other defaults and
not NULL-able at all?
Maybe a few should be empty strings instread

> You will find that most bad DML are kludges made in response to bad DDL.
You could say the same about requirements and design
You could say the same about feasibiliy and requirements
Sometimes it pays to jump in and build the damn system and deal with
the tweaks afterwards,

>based on two decades of cleaning up SQL.
No amount of experience gives anyone right to post unhelpfull,
self-indulgent replies ...
--CELKO-- wrote:
procedures. <<
> Oh, you want to write your own language and not bother with SQL! This
> behavior is one of many reasons that columns are not anything like
> fields and why I jump on newbies to actually read a book about the
> language before they start coding.
>
> Nobody should be so irresponsible as to give you that advice. Your
> code would not port, would not work properly, etc. what needs doing
> is a bit more education on your part instead of looking for kludges to
> save yourself some typing. Also, why aren't you using QA or a code
> editor instead of EM?
> SQL programmers think of the schema as a whole. The first place to
> look is the DDL and the Data Dictionary (which you probably do not
> have, if you have that many NULLs). Which of these columns really
> should be blanks, empty strings or other defaults and not NULL-able at
> all? I will bet most of them, based on two decades of cleaning up
> SQL.
> You will find that most bad DML are kludges made in response to bad
> DDL.|||>> And I thought the idea of newsgroups was to help ... <<
But there is an assumption that someone wants real help and not just a
kludge.
Wasn' t that what the accountants at Enron said -- this isn't about the
theory of accounting, etc. Why do you think a small budgets means
that you cannot do things right? The guy with the small budget is the
one who can least afford errors.
Correctness and maintainability are far more important than raw coding
speed. Hey, if it does not have to be right, the answer is always 42!
But later on you admit that you do not like to read things, so how do
you know what the rules are to make an informed decision about breaking
them? And somehow, you are always find a "good reason", such as your
dislike of typing in this thread :) And it probably has not worked,
but you do not know it yet.
Yes, it does matter. Do you go to a doctor who does not know the basic
concepts of his trade? Forget the fancy stuff, just the basic
concepts. It takes SIX years to become a Union Journeyman Carpenter in
New York State, but a kid with a few ws of MS Certificate cramming
thinks he is a programmer.
You might want to look at this:
http://www.apa.org/journals/psp/psp7761121.html
It is an article in the Journal of Personality and Social Psychology
entitled "Unskilled and Unaware of It: How Difficulties in Recognizing
One's Own Incompetence Lead to Inflated Self-Assessments"; the premise
is that people tend to hold overly favorable views of their abilities
in many social and intellectual domains. The authors suggest that this
overestimation occurs, in part, because people who are unskilled in
these domains suffer a dual burden: Not only do these people reach
erroneous conclusions and make unfortunate choices, but their
incompetence robs them of the metacognitive ability to realize it.
They tested some of the skills needed for programming.
The idea of learning, say, Normalization by "Trial & Error", looking at
training films or reading & writing a few thousand line of code seems a
bit .. expensive :)
This is the excuse that lazy and incompetent programmers use to cover
the fact that they do not know what they are doing. Does your code
include the external sources that provide data to your system? Do you
have a DFD for the system as a whole? I hope your end users are all SQL
programmers with about 15-20 years experience as well as domain experts
who can read that code when they need to use that system.
Do you know why you need a data dictionary? Do you even know what it
is? This is like an apprenice carpenter saying that "My house wiring
is the blueprint!"
One of my god-children and her husband have a small consulting company
in Atlanta. They are currently bidding on a job where the former
"Agile/XP/Cowboy Coder" decided that documentation is "just sooo anal!"
and was busy too refactoring code to bother with it. After a year of
"agile principles", the project is a failure. In fact, most Agile/XP
projects fail.
Since you do not llike to read, you might not have heard of the C3
(Chrysler Comprehensive Compensation) project. It was where XP began.
It was a payroll system that was to get around Y2K problems. It
started in 1996 and was cancelled in 2000 February. It had 1/3 of the
requirements originally promised and was so unusable that it was
scrapped by the end of 2000 and disappeared by 2002.
Maybe. Let's look at the specs and the data dictionary. Wait, yoyu
don't have those things.
You could say the same about requirements and design <<
We do say that! In fact, we measured the cost of errors in
requirements and design in the 1970's and later. This is one of the
major points of software engineering. In the classic DoD-2167 model
the total addition cost increased by about 10x at each step.
30 years of research disagrees with you. Check out the SEI, DoD, IBM,
any university research project on TCO of software, Barry Boehm and the
aerospace industry, etc. Did you see the piece on PBS on the levies
in New Orleans tonight? The Army Corp of Engineers They also built the
damn system and dealt with the tweaks afterwards.
What part of free speech and open forums confuses you? And when you
get over that hump of invincible igorance, you might find that you got
a lot of good advice instead of a kludge.

CONCAT function + SQL Sever 2005

I cant find a clear answer to the syntax of concat in for SQL 2005. Can anyone help.it's still the same old plus sign|||I figured out what I was doing wrong. I used text as my data type for the two fields I was trying to CONCAT. So when I did First_name + ' ' + Last_name is was treating the two columns as text and the blank space as a varchar. So i would execute.|||don't use the text type for such small fields as first and last names. text is for big blobs of text longer than 8000 chars. I don't know anyone with such a long name. :)

and in 2005, don't use text at all. use varchar(max) or nvarchar(max).

CONCAT function

Apologies for the glib answer but the concatinate function
you are looking for is the '+' that you already have.
The function that you are talking about (CONCAT) will work
however unless you are going to have a different number of
parameters then its not really worth it, and even then you
will need a bit of fancy code.
If it is then go ahead, but there is not a built in one.
if you have any further questions then please feel fee to
email me at peternolan67@.REMOVETHIS@.hotmail.com
Peter
Adam and Eve had many advantages but the principal one was
that they escaped teething.
Mark Twain

>--Original Message--
>Does SQL Server 2000 support the CONCAT SQL function?
>For example:
>
>-> 'SQLServer'
>I know it can be written as this:
>SELECT 'SQL' + 'Ser' + 'ver';
>
>My thoughts are to create a user-based function called
CONCAT. Are other
>thoughts on this?
>Thanks!
>.
>I tried to write this user-based function called CONCAT, yet is not working
properly. Only the first character is returned.
CREATE FUNCTION CONCAT (@.string1 nvarchar, @.string2 nvarchar)
RETURNS nvarchar AS
BEGIN
DECLARE @.fullstring nvarchar;
SELECT @.fullstring = @.string1 + @.string2;
return @.fullstring;
END
select dbo.concat('aaaa','bbbb')

> 'a'
"Peter The Spate" wrote:

> Apologies for the glib answer but the concatinate function
> you are looking for is the '+' that you already have.
> The function that you are talking about (CONCAT) will work
> however unless you are going to have a different number of
> parameters then its not really worth it, and even then you
> will need a bit of fancy code.
> If it is then go ahead, but there is not a built in one.
> if you have any further questions then please feel fee to
> email me at peternolan67@.REMOVETHIS@.hotmail.com
> Peter
> Adam and Eve had many advantages but the principal one was
> that they escaped teething.
> Mark Twain
>
> CONCAT. Are other
>|||You have to define a length for the nvarchar variables
/*for example*/
@.string1 nvarchar(100)
Keith
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:8E24AC41-ECE8-4E96-A716-5700F2C5BE50@.microsoft.com...
> I tried to write this user-based function called CONCAT, yet is not
working[vbcol=seagreen]
> properly. Only the first character is returned.
> CREATE FUNCTION CONCAT (@.string1 nvarchar, @.string2 nvarchar)
> RETURNS nvarchar AS
> BEGIN
> DECLARE @.fullstring nvarchar;
> SELECT @.fullstring = @.string1 + @.string2;
> return @.fullstring;
> END
>
> select dbo.concat('aaaa','bbbb')
>
> "Peter The Spate" wrote:
>|||I granted execute to a user called ENTRY, yet the user has to explicit state
the owner when making the call:
This fails:
select concat('a','b')
Server: Msg 195, Level 15, State 10, Line 1
'concat' is not a recognized function name.
This works
select dbo.concat('a'b')

>ab
How do I allow the user to use the dbo owned function without specifying the
owner?
Thanks!
"Keith Kratochvil" wrote:

> You have to define a length for the nvarchar variables
> /*for example*/
> @.string1 nvarchar(100)
> --
> Keith
>
> "Bevo" <Bevo@.discussions.microsoft.com> wrote in message
> news:8E24AC41-ECE8-4E96-A716-5700F2C5BE50@.microsoft.com...
> working
>|||> How do I allow the user to use the dbo owned function without specifying then">
> owner?
You cannot. The must specify the owner and function name in order to use
a user defined function.
Gert-Jan|||Books Online states this:
If an object is not qualified with the object owner when it is referenced
(for example, my_table instead of owner.my_table), SQL Server looks for an
object in the database in the following order:
Owned by the current user.
Owned by dbo.
According to this, the dbo function should be found. I this documentation
not correct?
"Gert-Jan Strik" wrote:

> You cannot. The must specify the owner and function name in order to use
> a user defined function.
> Gert-Jan
>|||However, user definined functions are a special case, different from other
objects. ALL user defined functions must include the owner name, even if it
is the current user.
Please read about User Defined Functions in the Books Online.
HTH
--
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:CA4058D0-9569-4602-AB81-BB525A75456E@.microsoft.com...[vbcol=seagreen]
> Books Online states this:
> If an object is not qualified with the object owner when it is referenced
> (for example, my_table instead of owner.my_table), SQL Server looks for an
> object in the database in the following order:
> Owned by the current user.
> Owned by dbo.
>
> According to this, the dbo function should be found. I this documentation
> not correct?
>
> "Gert-Jan Strik" wrote:
>
specifying the[vbcol=seagreen]|||Is there any workaround to this? Can I trick the database into thinking this
is a system function?
"Kalen Delaney" wrote:

> However, user definined functions are a special case, different from other
> objects. ALL user defined functions must include the owner name, even if i
t
> is the current user.
> Please read about User Defined Functions in the Books Online.
> --
> HTH
> --
> Kalen Delaney
> SQL Server MVP
> www.SolidQualityLearning.com
>
> "Bevo" <Bevo@.discussions.microsoft.com> wrote in message
> news:CA4058D0-9569-4602-AB81-BB525A75456E@.microsoft.com...
> specifying the
>
>|||No, the system functions are actually not objects in the normal sense. They
are almost like built in commands: substring, getdate, power, etc. The
system functions do not exist in any system tables, and their definitions
are not available in the TSQL language. There is no way to have the names
you give your UDFs be recognized by the parser, unless you get in and change
SQL Server's source code. In fact, supplying the owner name the way the
parser can tell that you are indicating a UDF, and not something else, like
a system function. Leaving off the owner name makes the parser think you are
specifying a system function, but then it realizes it has no built in
function of that name, so you get the error.
HTH
--
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:7AEA29F7-74D3-468A-9711-4829E36C3437@.microsoft.com...
> Is there any workaround to this? Can I trick the database into thinking
this[vbcol=seagreen]
> is a system function?
> "Kalen Delaney" wrote:
>
other[vbcol=seagreen]
it[vbcol=seagreen]
referenced[vbcol=seagreen]
for an[vbcol=seagreen]
documentation[vbcol=seagreen]
use[vbcol=seagreen]sqlsql

CONCAT function

Apologies for the glib answer but the concatinate function
you are looking for is the '+' that you already have.
The function that you are talking about (CONCAT) will work
however unless you are going to have a different number of
parameters then its not really worth it, and even then you
will need a bit of fancy code.
If it is then go ahead, but there is not a built in one.
if you have any further questions then please feel fee to
email me at peternolan67@.REMOVETHIS@.hotmail.com
Peter
Adam and Eve had many advantages but the principal one was
that they escaped teething.
Mark Twain

>--Original Message--
>Does SQL Server 2000 support the CONCAT SQL function?
>For example:
>-> 'SQLServer'
>I know it can be written as this:
>SELECT 'SQL' + 'Ser' + 'ver';
>
>My thoughts are to create a user-based function called
CONCAT. Are other
>thoughts on this?
>Thanks!
>.
>
I tried to write this user-based function called CONCAT, yet is not working
properly. Only the first character is returned.
CREATE FUNCTION CONCAT (@.string1 nvarchar, @.string2 nvarchar)
RETURNS nvarchar AS
BEGIN
DECLARE @.fullstring nvarchar;
SELECT @.fullstring = @.string1 + @.string2;
return @.fullstring;
END
select dbo.concat('aaaa','bbbb')

> 'a'
"Peter The Spate" wrote:

> Apologies for the glib answer but the concatinate function
> you are looking for is the '+' that you already have.
> The function that you are talking about (CONCAT) will work
> however unless you are going to have a different number of
> parameters then its not really worth it, and even then you
> will need a bit of fancy code.
> If it is then go ahead, but there is not a built in one.
> if you have any further questions then please feel fee to
> email me at peternolan67@.REMOVETHIS@.hotmail.com
> Peter
> Adam and Eve had many advantages but the principal one was
> that they escaped teething.
> Mark Twain
>
> CONCAT. Are other
>
|||You have to define a length for the nvarchar variables
/*for example*/
@.string1 nvarchar(100)
Keith
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:8E24AC41-ECE8-4E96-A716-5700F2C5BE50@.microsoft.com...
> I tried to write this user-based function called CONCAT, yet is not
working[vbcol=seagreen]
> properly. Only the first character is returned.
> CREATE FUNCTION CONCAT (@.string1 nvarchar, @.string2 nvarchar)
> RETURNS nvarchar AS
> BEGIN
> DECLARE @.fullstring nvarchar;
> SELECT @.fullstring = @.string1 + @.string2;
> return @.fullstring;
> END
>
> select dbo.concat('aaaa','bbbb')
>
> "Peter The Spate" wrote:
|||I granted execute to a user called ENTRY, yet the user has to explicit state
the owner when making the call:
This fails:
select concat('a','b')
Server: Msg 195, Level 15, State 10, Line 1
'concat' is not a recognized function name.
This works
select dbo.concat('a'b')

>ab
How do I allow the user to use the dbo owned function without specifying the
owner?
Thanks!
"Keith Kratochvil" wrote:

> You have to define a length for the nvarchar variables
> /*for example*/
> @.string1 nvarchar(100)
> --
> Keith
>
> "Bevo" <Bevo@.discussions.microsoft.com> wrote in message
> news:8E24AC41-ECE8-4E96-A716-5700F2C5BE50@.microsoft.com...
> working
>
|||> How do I allow the user to use the dbo owned function without specifying the
> owner?
You cannot. The must specify the owner and function name in order to use
a user defined function.
Gert-Jan
|||Books Online states this:
If an object is not qualified with the object owner when it is referenced
(for example, my_table instead of owner.my_table), SQL Server looks for an
object in the database in the following order:
Owned by the current user.
Owned by dbo.
According to this, the dbo function should be found. I this documentation
not correct?
"Gert-Jan Strik" wrote:

> You cannot. The must specify the owner and function name in order to use
> a user defined function.
> Gert-Jan
>
|||However, user definined functions are a special case, different from other
objects. ALL user defined functions must include the owner name, even if it
is the current user.
Please read about User Defined Functions in the Books Online.
HTH
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:CA4058D0-9569-4602-AB81-BB525A75456E@.microsoft.com...[vbcol=seagreen]
> Books Online states this:
> If an object is not qualified with the object owner when it is referenced
> (for example, my_table instead of owner.my_table), SQL Server looks for an
> object in the database in the following order:
> Owned by the current user.
> Owned by dbo.
>
> According to this, the dbo function should be found. I this documentation
> not correct?
>
> "Gert-Jan Strik" wrote:
specifying the[vbcol=seagreen]
|||Is there any workaround to this? Can I trick the database into thinking this
is a system function?
"Kalen Delaney" wrote:

> However, user definined functions are a special case, different from other
> objects. ALL user defined functions must include the owner name, even if it
> is the current user.
> Please read about User Defined Functions in the Books Online.
> --
> HTH
> --
> Kalen Delaney
> SQL Server MVP
> www.SolidQualityLearning.com
>
> "Bevo" <Bevo@.discussions.microsoft.com> wrote in message
> news:CA4058D0-9569-4602-AB81-BB525A75456E@.microsoft.com...
> specifying the
>
>
|||No, the system functions are actually not objects in the normal sense. They
are almost like built in commands: substring, getdate, power, etc. The
system functions do not exist in any system tables, and their definitions
are not available in the TSQL language. There is no way to have the names
you give your UDFs be recognized by the parser, unless you get in and change
SQL Server's source code. In fact, supplying the owner name the way the
parser can tell that you are indicating a UDF, and not something else, like
a system function. Leaving off the owner name makes the parser think you are
specifying a system function, but then it realizes it has no built in
function of that name, so you get the error.
HTH
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:7AEA29F7-74D3-468A-9711-4829E36C3437@.microsoft.com...
> Is there any workaround to this? Can I trick the database into thinking
this[vbcol=seagreen]
> is a system function?
> "Kalen Delaney" wrote:
other[vbcol=seagreen]
it[vbcol=seagreen]
referenced[vbcol=seagreen]
for an[vbcol=seagreen]
documentation[vbcol=seagreen]
use[vbcol=seagreen]

Saturday, February 25, 2012

complex query help - count

Hi,
I am trying to add an aggregate function to the query below but I am not
able to get the intended results. I want to get the count to return total
downloads by each user but my query returns the total downloads by all users
.
Current Output
1,ttt,rrr,6/1/3005,30
2,ddd,jjj,5/31/2005,30
3,ppp,yyy,5/20/2005,30
Desired Output
1,ttt,rrr,6/1/3005,15
2,ddd,jjj,5/31/2005,5
3,ppp,yyy,5/20/2005,10
QUERY:
select distinct spl. [main_id],fname,lname,subscription_ends,
count(download_id)
from
main m,
subscribers spl,
downloads
where
m.main_id = spl.main_id
and
spl.confnum like 'T12%'
and
subscription_ends > = Getdate()
group by
spl.[main_id],
fname,lname,subscription_ends
order by
subscription_ends DESC
CREATE TABLE [dbo].[Main] (
[main_id] [int] IDENTITY (1, 1) NOT NULL ,
[fname] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[lname] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
)
GO
CREATE TABLE [dbo].[subscribers] (
[main_id] [numeric](18, 0) NOT NULL ,
[confnum] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[subscription_starts] [datetime] NOT NULL
)
GO
CREATE TABLE [dbo].[Downloads] (
[main_id] [numeric](18, 0) NOT NULL ,
[download_id] [numeric](18, 0) NOT NULL
)
GOMike,
Try this,
select distinct spl. [main_id],fname,lname,subscription_ends,
count(main_id)
from
main m,
subscribers spl,
downloads
where
m.main_id = spl.main_id
and
spl.confnum like 'T12%'
and
subscription_ends > = Getdate()
and downloads.main_id = m.main_id
group by
spl.[main_id],
fname,lname,subscription_ends
order by
subscription_ends DESC
Thanks
"Mike" wrote:

> Hi,
> I am trying to add an aggregate function to the query below but I am not
> able to get the intended results. I want to get the count to return total
> downloads by each user but my query returns the total downloads by all use
rs.
> Current Output
> 1,ttt,rrr,6/1/3005,30
> 2,ddd,jjj,5/31/2005,30
> 3,ppp,yyy,5/20/2005,30
>
> Desired Output
> 1,ttt,rrr,6/1/3005,15
> 2,ddd,jjj,5/31/2005,5
> 3,ppp,yyy,5/20/2005,10
> QUERY:
> select distinct spl. [main_id],fname,lname,subscription_ends,
> count(download_id)
> from
> main m,
> subscribers spl,
> downloads
> where
> m.main_id = spl.main_id
> and
> spl.confnum like 'T12%'
> and
> subscription_ends > = Getdate()
> group by
> spl.[main_id],
> fname,lname,subscription_ends
> order by
> subscription_ends DESC
> CREATE TABLE [dbo].[Main] (
> [main_id] [int] IDENTITY (1, 1) NOT NULL ,
> [fname] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [lname] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> )
> GO
>
> CREATE TABLE [dbo].[subscribers] (
> [main_id] [numeric](18, 0) NOT NULL ,
> [confnum] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [subscription_starts] [datetime] NOT NULL
> )
> GO
> CREATE TABLE [dbo].[Downloads] (
> [main_id] [numeric](18, 0) NOT NULL ,
> [download_id] [numeric](18, 0) NOT NULL
> )
> GO
>

Friday, February 10, 2012

comparison between columns

How to compare the values between columns? I know there's a function "Greatest" in Oracle, do MS SQL have function similar to that?

And I want to create a view from a table, and one column 'll be selected from the 1 of the 4 related columns in table, say, If ColA is not null then the value is from ColA, if not , the value of the column in the view 'll be from ColB. How can i do this? Do I have to use store procedure?
( I know that's the result of poor normalization, but ... I'm not allowed to change th schema)sql/server apparently does not have anything as useful as the GREATEST function

unless someone else has a better idea, you'll have to use the CASE structure to build the equivalent --

select
(case
when a>=b and a>=c and a>=d then a
when b>=a and b>=c and b>=d then b
when c>=a and c>=b and c>=d then c
when d>=a and d>=b and d>=c then d
else a
end) as greatest

as for your other question, that's easy --

select coalesce(colA, colB) as ifAnullthenB

rudy
http://rudy.ca/|||What happens if you have Nulls?

Code:
---------------------------------------
create table #Tmp(a int, b int, c int, d int)

insert into #Tmp values(1, Null, Null, Null)
insert into #Tmp values(Null, 2, Null, Null)
insert into #Tmp values(Null, Null, 3, Null)
insert into #Tmp values(Null, Null, Null, 4)

insert into #Tmp values(5, 4, 3, 2)
insert into #Tmp values(3, 6, 4, 5)
insert into #Tmp values(4, 5, 7, 6)
insert into #Tmp values(5, 6, 7, 8)

select case
when a >= b and a >= c and a >= d then a
when b >= a and b >= c and b >= d then b
when c >= a and c >= b and c >= d then c
when d >= a and d >= b and d >= c then d
else a
end as greatest
from #Tmp

select case
when (b >= a or a is null) and (b >= c or c is null) and (b >= d or d is null) then b
when (c >= a or a is null) and (c >= b or b is null) and (c >= d or d is null) then c
when (d >= a or a is null) and (d >= b or b is null) and (d >= c or c is null) then d
else a
end as greatest
from #Tmp
---------------------------------------

Results:
---------------------------------------
greatest
----
1
NULL
NULL
NULL
5
6
7
8

greatest
----
1
2
3
4
5
6
7
8
---------------------------------------

Which is correct?