Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Monday, March 26, 2012

Proper use of the Right Function

RIGHT(value, numberofchars)
select right(username, 6) from ...
Seems like a reference to Books Online would have done this for you much
more efficiently than a forum post. :-)
Kevin G. Boles
Indicium Resources, Inc.
SQL Server MVP
kgboles a earthlink dt net
"fiaola" <fiaola@.mail.com> wrote in message
news:O9fJ6tLVIHA.5448@.TK2MSFTNGP04.phx.gbl...
> Hi,
> I tried to use the right function as, "Select right(UserName) as UN from
> Table1" and it returned "blank".
> It works well with Left. Im puzzled.
> Thanks
>
"fiaola" <fiaola@.mail.com> wrote in message
news:uIiqWJuVIHA.1184@.TK2MSFTNGP04.phx.gbl...
> Thanks for the reply. I did that, but it returned blank values. If i
> tried the LEFT function, it works well.
> My field is a character, and I could not figure out why it does not pickup
> the parameters requested.
>
What is the username you're using?
Perhaps the 6 right most characters are blank?
Can you post the actual code.
Thanks.

> "TheSQLGuru" <kgboles@.earthlink.net> wrote in message
> news:13ogib06s428b79@.corp.supernews.com...
>
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html

Proper use of the Right Function

Hi,
I tried to use the right function as, "Select right(UserName) as UN from
Table1" and it returned "blank".
It works well with Left. Im puzzled. :)
ThanksRIGHT(value, numberofchars)
select right(username, 6) from ...
Seems like a reference to Books Online would have done this for you much
more efficiently than a forum post. :-)
--
Kevin G. Boles
Indicium Resources, Inc.
SQL Server MVP
kgboles a earthlink dt net
"fiaola" <fiaola@.mail.com> wrote in message
news:O9fJ6tLVIHA.5448@.TK2MSFTNGP04.phx.gbl...
> Hi,
> I tried to use the right function as, "Select right(UserName) as UN from
> Table1" and it returned "blank".
> It works well with Left. Im puzzled. :)
> Thanks
>|||Thanks for the reply. I did that, but it returned blank values. If i tried
the LEFT function, it works well.
My field is a character, and I could not figure out why it does not pickup
the parameters requested.
"TheSQLGuru" <kgboles@.earthlink.net> wrote in message
news:13ogib06s428b79@.corp.supernews.com...
> RIGHT(value, numberofchars)
> select right(username, 6) from ...
> Seems like a reference to Books Online would have done this for you much
> more efficiently than a forum post. :-)
> --
> Kevin G. Boles
> Indicium Resources, Inc.
> SQL Server MVP
> kgboles a earthlink dt net
>
> "fiaola" <fiaola@.mail.com> wrote in message
> news:O9fJ6tLVIHA.5448@.TK2MSFTNGP04.phx.gbl...
>> Hi,
>> I tried to use the right function as, "Select right(UserName) as UN from
>> Table1" and it returned "blank".
>> It works well with Left. Im puzzled. :)
>> Thanks
>|||"fiaola" <fiaola@.mail.com> wrote in message
news:uIiqWJuVIHA.1184@.TK2MSFTNGP04.phx.gbl...
> Thanks for the reply. I did that, but it returned blank values. If i
> tried the LEFT function, it works well.
> My field is a character, and I could not figure out why it does not pickup
> the parameters requested.
>
What is the username you're using?
Perhaps the 6 right most characters are blank?
Can you post the actual code.
Thanks.
> "TheSQLGuru" <kgboles@.earthlink.net> wrote in message
> news:13ogib06s428b79@.corp.supernews.com...
>> RIGHT(value, numberofchars)
>> select right(username, 6) from ...
>> Seems like a reference to Books Online would have done this for you much
>> more efficiently than a forum post. :-)
>> --
>> Kevin G. Boles
>> Indicium Resources, Inc.
>> SQL Server MVP
>> kgboles a earthlink dt net
>>
>> "fiaola" <fiaola@.mail.com> wrote in message
>> news:O9fJ6tLVIHA.5448@.TK2MSFTNGP04.phx.gbl...
>> Hi,
>> I tried to use the right function as, "Select right(UserName) as UN from
>> Table1" and it returned "blank".
>> It works well with Left. Im puzzled. :)
>> Thanks
>>
>
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html

Proper use of Inner Join with nested select?

ok, i am a novice w/ sql queries, so this will probably be cake for
most of you if i can explain it properly.
I am trying to run a query against 2 tables, tbPlayers and tbResults
that are joined one to many by a PlayerId field. This query is used to
retrieve standings of poker tournament results, 1 record for each
player, an sum of money won from all tournaments, and a count of how
many times they have won any amount of money from a tournament.
SELECT tbPlayers.Name,
Sum(tbResults.MoneyWon) as [Prize Money]
(Select Count(MoneyWon) FROM tbResults WHERE MoneyWon > 0) as Cashes
FROM tbPlayers
INNER JOIN tbResults on tbResults.PlayerId = tbPlayers.Id
GROUP BY Players.Name
This query runs, but the value retrieved for 'Cashes' is incorrect, as
it brings back the count of ALL records in the table instead of just
those associated with a singe PlayerId.
Any thoughts would be greatly appreciated! (and i'll happily offer up a
free version of my Poker Tournament Director application once its ready
for beta ... which is soon!)Try something like this:
declare @.Player table (PlayerId int, name varchar(20))
insert @.Player values (1, 'jeff')
insert @.Player values (2, 'ed')
declare @.Results table (PlayerId int, MoneyWon int )
insert @.Results values(1, 100)
insert @.Results values(1, 0)
insert @.Results values(1, 1000)
insert @.Results values(2, -100)
insert @.Results values(2, 50)
SELECT p.Name,
Sum(r.MoneyWon) as [Prize Money],
Sum(case when MoneyWon > 0 then 1 else 0 end) as Cashes
FROM @.Player p
INNER JOIN @.Results r on p.PlayerId = r.PlayerId
GROUP BY p.Name|||Perfect!! Thank you - you the man!|||BriskDuck@.gmail.com wrote:
> ok, i am a novice w/ sql queries, so this will probably be cake for
> most of you if i can explain it properly.
> I am trying to run a query against 2 tables, tbPlayers and tbResults
> that are joined one to many by a PlayerId field. This query is used to
> retrieve standings of poker tournament results, 1 record for each
> player, an sum of money won from all tournaments, and a count of how
> many times they have won any amount of money from a tournament.
> SELECT tbPlayers.Name,
> Sum(tbResults.MoneyWon) as [Prize Money]
> (Select Count(MoneyWon) FROM tbResults WHERE MoneyWon > 0) as Cashes
> FROM tbPlayers
> INNER JOIN tbResults on tbResults.PlayerId = tbPlayers.Id
> GROUP BY Players.Name
> --
> This query runs, but the value retrieved for 'Cashes' is incorrect, as
> it brings back the count of ALL records in the table instead of just
> those associated with a singe PlayerId.
> Any thoughts would be greatly appreciated! (and i'll happily offer up a
> free version of my Poker Tournament Director application once its ready
> for beta ... which is soon!)
>
Try this :
SELECT tbPlayers.Name,
Sum(tbResults.MoneyWon) as [Prize Money],cashes.[WinCount]
FROM tbPlayers
INNER JOIN tbResults on tbResults.PlayerId = tbPlayers.Id
INNER JOIN (SELECT [PlayerId],COUNT([MoneyWon]) AS [WinCount] FROM
tbResults GROUP BY [PlayerId]) AS Cashes ON tbResults.[PlayerId] =
cashes.[PlayerId]
GROUP BY tbPlayers.Id,tbPlayers.[Name],cashes.WinCount
-JayDial|||JeffB wrote:
> Try something like this:
>
> declare @.Player table (PlayerId int, name varchar(20))
> insert @.Player values (1, 'jeff')
> insert @.Player values (2, 'ed')
> declare @.Results table (PlayerId int, MoneyWon int )
> insert @.Results values(1, 100)
> insert @.Results values(1, 0)
> insert @.Results values(1, 1000)
> insert @.Results values(2, -100)
> insert @.Results values(2, 50)
> SELECT p.Name,
> Sum(r.MoneyWon) as [Prize Money],
> Sum(case when MoneyWon > 0 then 1 else 0 end) as Cashes
> FROM @.Player p
> INNER JOIN @.Results r on p.PlayerId = r.PlayerId
> GROUP BY p.Name
>
Whoa nevermind, forget mine. This looks much better! ;)sql

Wednesday, March 7, 2012

Programmatically alter grouping

Hi Everyone:
We are evaluating the SQL Server Reporting Services for use in our
current web project. The users will have the ability to select report
fields that they can group on and filter on, via a web page.
The materials I have read so far have not touched on how one can
programmatically alter groups on a report and also how should the
report that offers several grouping options to the user be designed(as
in whether the report should have all possible groupings defined at
design time and "disabled" by default)?
In Crystal Report we remember creating the various goups and
"deactivating" them at design time and programmatically altering the
group hierarchy at run time.
If anyone has any information on this issue, it would be very much
appreciated. Thanks a lot.
-Raghu.http://blogs.msdn.com/chrishays/archive/2004/07/15/184646.aspx
--
This post is provided 'AS IS' with no warranties, and confers no rights. All
rights reserved. Some assembly required. Batteries not included. Your
mileage may vary. Objects in mirror may be closer than they appear. No user
serviceable parts inside. Opening cover voids warranty. Keep out of reach of
children under 3.
"Raghu" <raghu_seshadri@.hotmail.com> wrote in message
news:5c2d0972.0407150214.106d400d@.posting.google.com...
> Hi Everyone:
> We are evaluating the SQL Server Reporting Services for use in our
> current web project. The users will have the ability to select report
> fields that they can group on and filter on, via a web page.
> The materials I have read so far have not touched on how one can
> programmatically alter groups on a report and also how should the
> report that offers several grouping options to the user be designed(as
> in whether the report should have all possible groupings defined at
> design time and "disabled" by default)?
> In Crystal Report we remember creating the various goups and
> "deactivating" them at design time and programmatically altering the
> group hierarchy at run time.
> If anyone has any information on this issue, it would be very much
> appreciated. Thanks a lot.
> -Raghu.|||Your blog made an interesting reading. I will give this technique a
try. Thank you very much for your assistance.
Regards,
Raghu.|||Hi Chris:
I tried the grouping technique explained in your blog. It worked like
a charm. Thanks a lot for your help.
Regards,
Raghu.

Programmatically Accessing an SQLDataSource with a "SELECT COUNT(*)" query.

I've found example code of accessing an SQLDataSource and even have it working in my own code - an example would be

Dim datastuff As DataView = CType(srcSoftwareSelected.Select(DataSourceSelectArguments.Empty), DataView)

Dim row As DataRow = datastuff.Table.Rows(0)
Dim installtype As Integer = row("InstallMethod")
Dim install As String = row("Install").ToString
Dim notes As String = row("Notes").ToString

The above only works on a single row, of course. If I needed more, I know I can loop it.

The query in srcSoftwareSelected is something like "SELECT InstallMethod, Install, Notes FROM Software"

My problem lies in trying to access the data in a simliar way when I'm using a SELECT COUNT query.

Dim datastuff As DataView = CType(srcSoftwareUsage.Select(DataSourceSelectArguments.Empty), DataView)
Dim row As DataRow = datastuff.Table.Rows(0)
Dim count As Integer = row("rowcnt")

The query here is "SELECT COUNT(*) as rowcnt FROM Software"

The variable count is 1 every time I query this, no matter what the actual count is. I know I've got to be accessing the incorrect data member in the 2nd query because a gridview tied to srcSoftwareUsage (the SQLDataSource) always displays the correct value.

Where am I going wrong here?


The following should work.

Dim datastuffAs System.Data.DataView =CType(srcSoftwareUsage.Select(DataSourceSelectArguments.Empty), System.Data.DataView)

Dim drAs System.Data.DataRow = datastuff .Table.Rows(0)

Dim mycountAsString = Convert.ToInt32(dr("rowcnt")).ToString()

'Label1.Text = mycount

|||

Hi there,

Aren't you getting the row count from your SELECT COUNT query (1 row obviously)? Instead of getting the result value from that query?

gonzzas

|||

It's very similar to what I've tested out, but that exact code will show that mycount = "1" instead of the actual value.

What is interesting is the GridView control I set up on the test page is outputting the correct result.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="srcSoftwareUsage" Width="527px">
<Columns>
<asp:BoundField DataField="rowcnt" HeaderText="rowcnt" ReadOnly="True" SortExpression="rowcnt" />
</Columns>
</asp:GridView>

Now, it's obviously accessing the column named rowcnt. I can debug my code and manually look at the column values in DataView.Table.Rows(0) and it shows the value 1 and nothing more.

|||

Yes, I can use either code to get the correct count from my query. What is your SqlDataSource code?

Here is what I tested:

Dim dvAs System.Data.DataView =CType(SqlDataSource2.Select(DataSourceSelectArguments.Empty), System.Data.DataView)

Dim rowAs System.Data.DataRow = dv.Table.Rows(0)

' For Each row As System.Data.DataRow In dv.Table.Rows

Dim mycountAsString = Convert.ToInt32(row("rowcnt")).ToString()

Label2.Text = mycount

' Next

|||

Murphy's Law probably applies as I didn't give you thecomplete story - I naively thought this part shouldn't matter as it'sthe table output is identical.

It appears to be my sql query.

I'm not actually looking for the count of rows in the Software table, but I'm looking for the count of times a particular row in Software is referenced by 2 other tables - RoleSoft and TeamSoft

With my simple query above, both the code and GridView worked. With this one - the GridView works, the code doesn't.

SELECT COUNT(*) AS rowcnt FROM (SELECT Role, Software FROM RoleSoft WHERE (Software = @.Id) UNION ALL SELECT Team, Software FROM TeamSoft WHERE (Software = @.Id)) AS derivedtbl_1

I thought it was a moot point as the table output appears identical from each query. Obviously I'm wrong. I'm imagining the derivedtbl_1 is probably where I'm getting bogus data in the code.

1> SELECT COUNT(*) AS rowcnt FROM (SELECT Role, Software FROM RoleSoft WHERE (Software = 2) UNION ALL SELECT Team, Software FROM TeamSoft WHERE (Software = 2))
AS derivedtbl_1
2> go
rowcnt
----
3

(1 rows affected)
1> SELECT COUNT(*) as rowcnt FROM Software
2> go
rowcnt
----
8

(1 rows affected)

|||

Bah. I figured it out. It wasn't even the SQL statement. I had updated the @.Id parameter in the srcSoftwareUsage_Selecting event handler and I misused a global variable. It kept setting @.Id to 1 and the count for that Id was always 1.

Now I feel stupid for wasting your time and mine on this. Thanks for the help, though.

Saturday, February 25, 2012

Programaticly setting the value of a Select Query Property.

I have a query in which I'd like to use the username of the user currently logged in. The expression im using to retrieve the username is: Membership.GetUser().UserName.
Currently I have the following:
<asp:SqlDataSource ID="ProjectSource" runat="server" ConnectionString="<%$ ConnectionStrings:Code %>"
ProviderName="<%$ ConnectionStrings:Code.ProviderName %>" SelectCommand="Select Name, Namespace from Project where User = $Username">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="$Username" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="ProjectSource" />

I'd somehow like to set up $Username to be equivlent to Membership.GetUser().UserName.I'd be interested to hear of a better way, however, currently, I cheat. I stuff things like that when they authenticate to session variables (I only have 3 in my current project). Then I pull them in the sqldatasources from there.|||Yeah, my solution doesnt look to be much better. Currently Im Setting the default value every time I need to execute a query.

programatically obtain primary keys

Given a table, is there a way to look into the systables and obtain the primary keys of that table via a select statement?

Thanks,

Phil

I got it nevermind.

select s.name as TABLE_SCHEMA, t.name as TABLE_NAME

, k.name as CONSTRAINT_NAME, k.type_desc as CONSTRAINT_TYPE
, c.name as COLUMN_NAME, ic.key_ordinal AS ORDINAL_POSITION
from sys.key_constraints as k
join sys.tables as t
on t.object_id = k.parent_object_id
join sys.schemas as s
on s.schema_id = t.schema_id
join sys.index_columns as ic
on ic.object_id = t.object_id
and ic.index_id = k.unique_index_id
join sys.columns as c
on c.object_id = t.object_id
and c.column_id = ic.column_id
order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME, ORDINAL_POSITION;

Monday, February 20, 2012

programatically change sqldatasource select statement

Hi Everyone,

I am trying to change the select statement of an sqldatasource if a check box is checked.

I am using theSqlDataSourceSelectingEventArgs but i can't get it to work, anyone got any pointers?

Code Behind

ProtectedSub LocMan_Searching(ByVal senderAsObject,ByVal eAs SqlDataSourceSelectingEventArgs)Handles LocManSearch.Selecting

If cb_Today.Checked =TrueThen

LocManSearch.SelectCommand ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%' + " & dd_Area.SelectedValue.ToString() &"+ '%') AND [available] LIKE '%' + " &Date.Today &"+ '%')"

Else : LocManSearch.SelectCommand ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%' + " & dd_Area.SelectedValue.ToString() &" + '%')"

EndIf

EndSub

My SQLDATSOURCE

<asp:SqlDataSourceID="LocManSearch"runat="server"ConnectionString="<%$ ConnectionStrings:MYLOCDEVConnectionString %>">

<SelectParameters>

<asp:ControlParameterControlID="dd_Area"Name="area"PropertyName="SelectedValue"

Type="String"/>

</SelectParameters>

</asp:SqlDataSource>

Thanks in advance

Chris

I have always just used a string for my SQL statement assigned to a variable and just changed what the variable is assigned to, such as:

If checkbox.checked = true

SQLstr = "Select *..."

Else

SQLstr = "Select Column1..."

End if

|||

Thanks for the reply,

How then do i pass the string to my sqldatasource as the select command?


Chris

|||

Hi Chris,

Thanks again for the reply. I have made the change you suggested and moved the sub to the page load event handler which made it work. Problem is i get SQL errors.. Can anyone see where my select might be wrong?

Cheers


Chris

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

Dim SQLstrAsString

If cb_Today.Checked =TrueThen

SQLstr ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%' + " & dd_Area.SelectedValue.ToString() &"+ '%') AND [available] LIKE '%' + " &Date.Today &"+ '%')"

Else : SQLstr ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%' + " & dd_Area.SelectedValue.ToString() &" + '%')"

EndIf

LocManSearch.SelectCommand = SQLstr

EndSub

|||

Besides the fact that you suffer from possibly getting SQL Injection attacks because you are using sql string concatenation instead of either parameterized queries or encoded strings, here is your problem:

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

Dim SQLstrAsString

If cb_Today.Checked =TrueThen

SQLstr ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%" & dd_Area.SelectedValue.ToString() &"%') AND [available] LIKE '%" &Date.Today &"%')"

Else : SQLstr ="SELECT * FROM [LocMan_CV] WHERE ([area] LIKE '%" & dd_Area.SelectedValue.ToString() &"%')"

EndIf

Programatic replication

I have SELECT access to a database that is very, very slow to work with to
the point where I am looking to replicate at least one table to my own
server to use the data locally. What is the best way to check for new
records if the table key is not incremental? I prefer not to try a "If
exists" on the entire databse every minute or due to the speed issues.Hi
If you are allowed to change the structure of the table then you may want to
add a rowversion column. If not maybe you should use log shipping to recreat
e
the whole databases?
John
"Dave S." wrote:

> I have SELECT access to a database that is very, very slow to work with to
> the point where I am looking to replicate at least one table to my own
> server to use the data locally. What is the best way to check for new
> records if the table key is not incremental? I prefer not to try a "If
> exists" on the entire databse every minute or due to the speed issues.
>
>