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

Friday, March 30, 2012

how to diaplay date in MM/dd/yyyy format

how to display date in mm/dd/yy using select query ( i have dates which are in mm/dd/yyyyy format but when i run a query it displaying yyyy-mm-dd format).i want to display date in mm/dd/yyyy format so how to write select query for that

This 'should' work:

SELECT convert( varchar(10), MyColumn, 101 )

For example, using today's date:

SELECT convert( varchar(10), getdate(), 101 )


-
05/25/2007

|||what is this 101 , 102 in code|||

It the style number which indicates how the system should transform your data.

Here is more detail.

http://msdn2.microsoft.com/en-us/library/ms187928.aspx

|||thanks a lot MVPsql

Monday, March 26, 2012

How to determine ROWCOUNT without executing the select statement

I'm selecting data from a large table in a paged manner by using the
ROW_NUMBER ranking function in a function like the one shown below... I
want the function to also return the total number of rows in the dataset
AFTER the primary select is issued but before the paged data is selected
out. In other words, if there are 10,000 rows, and 3500 of them get
selected by the where clause, but the paging only returns 101 .. 200, I
want the total rows output to be set to 3500.
The way this is written currently, I use @.@.ROWCOUNT, but only get the
page size (eg 100). Is there an easy way to get the primary data set
size without resorting to memory or temporary tables, and without
executing the main query twice'
-mdb
#############################
PROCEDURE [dbo].[GetTablePagedAndSorted]
(
@.tableName nvarchar(100),
@.columnList varchar(2000),
@.sortExpression nvarchar(100),
@.whereClause varchar(2000),
@.startRowIndex int,
@.maximumRows int,
@.totalRows int OUTPUT
) AS
IF (LEN(@.whereClause) = 0) SET @.whereClause = '1=1'
-- Issue query
DECLARE @.sql nvarchar(4000)
SET @.sql = 'SELECT ' + @.columnList + ',RowRank '
SET @.sql = @.sql + ' FROM (
SELECT ' + @.columnList + ', ROW_NUMBER() OVER (ORDER BY ' +
@.sortExpression + ') AS RowRank
FROM ' + @.tableName + '
WHERE (' + @.whereClause + ')
) AS TableWithRowNumbers '
IF (@.maximumRows > 0)
BEGIN
SET @.sql = @.sql + '
WHERE RowRank >= ' + CONVERT(nvarchar(10), @.startRowIndex) +
'
AND RowRank < (' + CONVERT(nvarchar(10), @.startRowIndex) +
' + ' + CONVERT(nvarchar(10), @.maximumRows) + ')'
END
-- Execute the SQL query
PRINT @.sql
EXEC sp_executesql @.sql
SET @.totalRows = @.@.ROWCOUNT
######################################You could put the result into a temp. table. Or you could create a SELECT
COUNT(*) to get the count before you do the actual SELECT. I guess the
question is how important is it to know the intermediate result set size -
is it worth the extra inefficiency?
"Michael Bray" <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in message
news:Xns99E1B6650917Embrayctiusacom@.207.46.248.16...
> I'm selecting data from a large table in a paged manner by using the
> ROW_NUMBER ranking function in a function like the one shown below... I
> want the function to also return the total number of rows in the dataset
> AFTER the primary select is issued but before the paged data is selected
> out. In other words, if there are 10,000 rows, and 3500 of them get
> selected by the where clause, but the paging only returns 101 .. 200, I
> want the total rows output to be set to 3500.
> The way this is written currently, I use @.@.ROWCOUNT, but only get the
> page size (eg 100). Is there an easy way to get the primary data set
> size without resorting to memory or temporary tables, and without
> executing the main query twice'
> -mdb
> #############################
> PROCEDURE [dbo].[GetTablePagedAndSorted]
> (
> @.tableName nvarchar(100),
> @.columnList varchar(2000),
> @.sortExpression nvarchar(100),
> @.whereClause varchar(2000),
> @.startRowIndex int,
> @.maximumRows int,
> @.totalRows int OUTPUT
> ) AS
> IF (LEN(@.whereClause) = 0) SET @.whereClause = '1=1'
> -- Issue query
> DECLARE @.sql nvarchar(4000)
> SET @.sql = 'SELECT ' + @.columnList + ',RowRank '
> SET @.sql = @.sql + ' FROM (
> SELECT ' + @.columnList + ', ROW_NUMBER() OVER (ORDER BY ' +
> @.sortExpression + ') AS RowRank
> FROM ' + @.tableName + '
> WHERE (' + @.whereClause + ')
> ) AS TableWithRowNumbers '
> IF (@.maximumRows > 0)
> BEGIN
> SET @.sql = @.sql + '
> WHERE RowRank >= ' + CONVERT(nvarchar(10), @.startRowIndex) +
> '
> AND RowRank < (' + CONVERT(nvarchar(10), @.startRowIndex) +
> ' + ' + CONVERT(nvarchar(10), @.maximumRows) + ')'
> END
> -- Execute the SQL query
> PRINT @.sql
> EXEC sp_executesql @.sql
> SET @.totalRows = @.@.ROWCOUNT
> ######################################
>|||"Mike C#" <xyz@.xyz.com> wrote in
news:OG9RqcZIIHA.4584@.TK2MSFTNGP03.phx.gbl:
> You could put the result into a temp. table. Or you could create a
> SELECT COUNT(*) to get the count before you do the actual SELECT. I
> guess the question is how important is it to know the intermediate
> result set size - is it worth the extra inefficiency?
> "Michael Bray" <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in
> message news:Xns99E1B6650917Embrayctiusacom@.207.46.248.16...
>> I'm selecting data from a large table in a paged manner by using the
>> ROW_NUMBER ranking function in a function like the one shown below...
>> I want the function to also return the total number of rows in the
>> dataset AFTER the primary select is issued but before the paged data
>> is selected out. In other words, if there are 10,000 rows, and 3500
>> of them get selected by the where clause, but the paging only returns
>> 101 .. 200, I want the total rows output to be set to 3500.
Thanks, but as I said I do not want to use temporary tables, as this will
absolutely swamp my tempdb due to the potential size of the query results.
I considered your other suggestion previously, but then the question is how
do I get the results of an EXEC into a variable? Keep in mind that I have
to build the sql dynamically, and thus require sp_executesql. The
following syntax doesn't work:
SET @.totalRows = (EXEC sp_executesql @.mySqlStatement) ' doesn't parse
If I can find the solution to how to set a variable based on a dynamic sql
statement then I will be set.
-mdb|||Michael Bray <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in
news:Xns99E2544576DFAmbrayctiusacom@.207.46.248.16:
> Thanks, but as I said I do not want to use temporary tables, as this
> will absolutely swamp my tempdb due to the potential size of the query
> results. I considered your other suggestion previously, but then the
> question is how do I get the results of an EXEC into a variable? Keep
> in mind that I have to build the sql dynamically, and thus require
> sp_executesql. The following syntax doesn't work:
> SET @.totalRows = (EXEC sp_executesql @.mySqlStatement) ' doesn't parse
> If I can find the solution to how to set a variable based on a dynamic
> sql statement then I will be set.
>
OK I found the solution - sp_executesql can actually accept input and
output parameters!!
See the wonderful article at:
http://www.sommarskog.se/dynamic_sql.html
-mdb|||Oops, I see you already found that
"Michael Bray" <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in message
news:Xns99E26438875B7mbrayctiusacom@.207.46.248.16...
> Michael Bray <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in
> news:Xns99E2544576DFAmbrayctiusacom@.207.46.248.16:
>> Thanks, but as I said I do not want to use temporary tables, as this
>> will absolutely swamp my tempdb due to the potential size of the query
>> results. I considered your other suggestion previously, but then the
>> question is how do I get the results of an EXEC into a variable? Keep
>> in mind that I have to build the sql dynamically, and thus require
>> sp_executesql. The following syntax doesn't work:
>> SET @.totalRows = (EXEC sp_executesql @.mySqlStatement) ' doesn't parse
>> If I can find the solution to how to set a variable based on a dynamic
>> sql statement then I will be set.
> OK I found the solution - sp_executesql can actually accept input and
> output parameters!!
> See the wonderful article at:
> http://www.sommarskog.se/dynamic_sql.html
> -mdb|||sp_executesql does take output params
"Michael Bray" <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in message
news:Xns99E2544576DFAmbrayctiusacom@.207.46.248.16...
> "Mike C#" <xyz@.xyz.com> wrote in
> news:OG9RqcZIIHA.4584@.TK2MSFTNGP03.phx.gbl:
>> You could put the result into a temp. table. Or you could create a
>> SELECT COUNT(*) to get the count before you do the actual SELECT. I
>> guess the question is how important is it to know the intermediate
>> result set size - is it worth the extra inefficiency?
>> "Michael Bray" <mbrayATctiusaDOTcom@.you.figure.it.out.com> wrote in
>> message news:Xns99E1B6650917Embrayctiusacom@.207.46.248.16...
>> I'm selecting data from a large table in a paged manner by using the
>> ROW_NUMBER ranking function in a function like the one shown below...
>> I want the function to also return the total number of rows in the
>> dataset AFTER the primary select is issued but before the paged data
>> is selected out. In other words, if there are 10,000 rows, and 3500
>> of them get selected by the where clause, but the paging only returns
>> 101 .. 200, I want the total rows output to be set to 3500.
> Thanks, but as I said I do not want to use temporary tables, as this will
> absolutely swamp my tempdb due to the potential size of the query results.
> I considered your other suggestion previously, but then the question is
> how
> do I get the results of an EXEC into a variable? Keep in mind that I have
> to build the sql dynamically, and thus require sp_executesql. The
> following syntax doesn't work:
> SET @.totalRows = (EXEC sp_executesql @.mySqlStatement) ' doesn't parse
> If I can find the solution to how to set a variable based on a dynamic sql
> statement then I will be set.
> -mdb

Friday, March 23, 2012

How to determine Count of ties in MDX?

I need to determine the number of values in a set that are non-unique in the set.

In SQL, I would do the following:

select sum(value_count) as Ties

from (select value, count(*) as value_count

from source

group by value

having count(*) >1

)

In MDX, I have a set defined in a query that is passed into several custom statistical functions. I would like to be able to accomplish this without writing another external function, as it seems the sort of thing that should be easy...

Here is the query I'm trying to plug this into. Suggestions welcome.

with

set [data] as ( nonempty({

[Sample Date].[Time].[Day] }) *{ [Measures].[Parm Value] } )

MEMBER [Sen's Slope] as 'Statistics.Sen_Slope({[data]})'

MEMBER [Kendall's Tau] as 'Statistics.KENDALLS_TAU({[data]})'

MEMBER [Significant] as 'Statistics.Significance({[data]})'

MEMBER [MK_Z] as 'Statistics.Mann_Kendall_Z({[data]})'

member [measures].[Samples] as [data].count

member [measures].[Average] as avg([data])

member [measures].[Median] as Median([data])

member [measures].[Last Sample] as tail([data],1).item(0)

MEMBER [Ties] as '0'

select {[Samples],[Average],[Median],[Last Sample], [Kendall's Tau], [Sen's Slope], [MK_Z], [Significant], [Ties] } on 0

FROM ( SELECT ( [Sample Date].[Time].[2002 Q4]:[Sample Date].[Time].[2006 Q3] ) on 0,

{([Site Hierarchy].[Site Hierarchy].[Site ID].[0829SD6001] ,

[Analysis Parameter].[Analysis Parameter].[Acidity (ACD)])} ON 1

FROM [Sample Data])

;

Hi Clayton,

This sample from Adventure Works, where value is [Reseller Order Quantity], seems to work:

SQL query:

>>

select sum(order_count) as Ties
from
(select OrderQuantity, count(*) as order_count
from
(select ProductKey, sum(OrderQuantity) as OrderQuantity
from dbo.FactResellerSales
group by ProductKey) ps
group by OrderQuantity
having count(*) > 1) oc

87

>>

MDX query:

>>

With

Member [Measures].[PrdTies] as

Count(Filter(Order(NonEmpty(

[Product].[Product].[Product].Members,

{[Measures].[Reseller Order Quantity]}),

[Measures].[Reseller Order Quantity], BDESC) as OrdPrds,

(OrdPrds.CurrentOrdinal < OrdPrds.Count

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal)))

OR (OrdPrds.CurrentOrdinal > 1

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal-2)))))

select {[Measures].[PrdTies]} on 0

from [Adventure Works]

PrdTies
87

>>

|||

Deepak,

Thanks for the thourough response. I've done some testing, comparing results from the MDX you wrote to the ADOMD CLR proc I wrote, and I was getting different results. I've traced through the CLR version and manually counted the values in the set, and the CLR proc was correct. I've clipped out the relevant code in case you want to compare results. It may be the differences in how I'm calling the CLR functions by passing in a set versus the Measure method, which is working over the complete set of data from the subcube query.

Here is your test MDX query, with a measure added for the CLR function. In this case, both methods return the same count, as expected. I'm just curious as to what might be causing me to get dfferent counts between the two methods when used in my cube...

With

set [data] as ( NonEmpty([Product].[Product].[Product].Members)

*([Measures].[Reseller Order Quantity]) )

member [CountOfTies] as 'Statistics.CountOfTies({[data]})'

Member [Measures].[PrdTies] as

Count(Filter(Order(NonEmpty(

[Product].[Product].[Product].Members,

{[Measures].[Reseller Order Quantity]}),

[Measures].[Reseller Order Quantity], BDESC) as OrdPrds,

(OrdPrds.CurrentOrdinal < OrdPrds.Count

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal)))

OR (OrdPrds.CurrentOrdinal > 1

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal-2)))))

select {[Measures].[PrdTies], [CountOfTies]} on 0

from [Adventure Works];

Assembly code:

using System;

using System.Collections;

using Microsoft.AnalysisServices;

using Microsoft.AnalysisServices.AdomdServer;

namespace Statistics

{

public sealed class Statistics

{

private Statistics()

{

}

[CLSCompliant(false)]

// function to return a sum of the counts for tied values

public static Object CountOfTies(Set data1)

{

try

{

//number of Tuples in the set

Int32 v = data1.Tuples.Count;

if (v > 1)

{

//dimension a new array to hold values for passing into GetCountOfTies()

Double[] ValueArray;

ValueArray = new Double[v];

MDXValue mdxval;

Int32 i = 0;

// convert tuple set into an array

foreach (Tuple t in data1.Tuples)

{

mdxval = t;

ValueArray[i++] = mdxval.ToDouble();

}

// get array of any ties

Int32[] ResultArray = GetCountOfTies(ValueArray);

//sum counts to get results to return

i = 0;

foreach (Int32 j in ResultArray)

{i = i + j;}

return i;

}

else {return 0;}

}

catch (Exception e)

{

Console.WriteLine(e);

return "ERROR";

}

}

private static Int32[] GetCountOfTies(double[] doubleArray)

{

//create an array of counts of unique values, where there are ties in values.

//the resulting array will contain one element for each value with ties.

Array.Sort(doubleArray);

ArrayList numbers = new ArrayList();

double? lastVal = null;

int currentCount = 0;

foreach (double val in doubleArray)

{

if (lastVal != null && lastVal != val)

{

if (currentCount > 1)

numbers.Add(currentCount);

currentCount = 1;

}

else

{currentCount++;}

lastVal = val;

}

return (Int32[])numbers.ToArray(typeof(Int32));

}

}

}

Monday, March 19, 2012

how to detach a read only database from Sql Express

Need help

I made a mistake an attached a read only database to the server (now it is grey marked).

When I try to select this read only database in the MS SQL Server Management Studio, the server hangs up.

I removed the read only attribute from the .mdf and .ldf File and made a reboot of the server. Still the same problem.

How can I detach this read only database or how can I set the attribute to read/write (always hangs up the server, when I try to access this db)

I tried also:

alter database readOnly_dbname set read_write

or

USE master;
GO
EXEC sp_dboption 'readOnly_dbname', 'read only', 'FALSE';

Many thanks for an answer.

Kusi

Did you use sp_detachdb 'DbName' ?


Jens K. Suessmeyer

http://www.sqlserver2005.de

|||

I have the same problem. In management studio, the only thing that you can do is to make delete on the read-only database. You will have an error, but the database will be well released from SQL Server. I didn't find a way to make it back non read-only... by scripting or in the management studio.

Someone has a solution for that problem?

|||

I found a solution. The issue is related to the files security.

Be sure that the .mdf and .ldf files have the NETWORK SERVICE and the SQLServer2005MSSQLUser$YourPc$YourSqlInstanceName security users with Full Control permission checked on them.

Monday, March 12, 2012

How to Derive Parameters in Ad Hoc SELECT statements

Hi,

If I have ad hoc SQL statements created by users, which could be parameterized, how could I derive the parmeters at runtime. I cannot use CommandBuilder.DeriveParameters() as that is for StoredProcedures only.

Just use Split on the SQL string? Or is there a better way, such as a third-party .Net Component?

Thanks

John

We need more input on your problem. What does it mean that the users are creating the SQL Strings on their own, how does one look like ?

Jens K. Suessmeyer.

http://www.sqlserver2005.de
--|||

Hi,

The User's created SQL could be anything (they are writing a report!), but here is a trivial example

SELECT CustomerID, CustomerName FROM Customers WHERE CustomerID = @.CustomerID

Clearly, I have to Pop up a Window to the User for them to supply the actual run time value for @.CustomerID. Just like MS Access or the VS2005's Dataset Designer's Query Builder. Once I have the values I can populate Parameters Collection.

I was hoping someone would have some advise over Parsing SQL strings.

Thanks

John

|||

Best thing would be to regex the string and search for the matches within the string.

Jens K.

|||

Hi,

I've been looking at the General SQL Parser component, and it looks like I can simply get to the Field, Parameter pairs using this. Product is easily found, just do a Web search.

But, out of interests, Jens. Do you have contacts within the Microsoft Dev teams to find out how they do it in VS2005's Dataset Designer's Query Builder and Management Studio's Query Designer?

Rgds

John

Wednesday, March 7, 2012

How to delete so good?

I ask to you. How to delete data at table A that exist at table B.
Usually I write like this:
DELETE FROM TA where NOID in (SELECT NOID FROM TB).
But it can works, if at table A (TA) has 1 field to be primary key. If table
A (TA) has 4 fields to be primary key. How its syntax so good?>> But it can works, if at table A (TA) has 1 field to be primary key. If
You can re-write it with EXISTS like:
DELETE FROM tbl1
WHERE EXISTS ( SELECT *
FROM tbl2
WHERE tbl2.col1 = tbl1.col1
AND tbl2.col2 = tbl1.col2
AND tbl2.col3 = tbl1.col3
AND tbl2.col4 = tbl1.col4 ) ;
Anith|||Let's assume that in TB has a primary key that consists of SSN and
DateOfBirth. Let's also assume that TA basically contains the same type of
records but is denormalized so that the same key is consolidated in a column
called PersonID.
delete from TA where PersonID in (select SSN + DateOfBirth from TB)
"Bpk. Adi Wira Kusuma" <adi_wira_kusuma@.yahoo.com.sg> wrote in message
news:ek6us%23hjFHA.3164@.TK2MSFTNGP15.phx.gbl...
>I ask to you. How to delete data at table A that exist at table B.
> Usually I write like this:
> DELETE FROM TA where NOID in (SELECT NOID FROM TB).
> But it can works, if at table A (TA) has 1 field to be primary key. If
> table
> A (TA) has 4 fields to be primary key. How its syntax so good?
>