Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Monday, March 26, 2012

How to Change Query Type ?(Mangagement Studio)

Why the "Change Type" Button of the "Query Designer Toolbar " is alwayse Disable(gray color) ,then how can i switch the query between "selelct","update","Insert" and "Delete"? I am using Nov 7 released 180 Days Trial Version.(Sql Server Management Studio)

Thannks!

The Query toolbar is associated with Query Designer documents. The only way to display such a document in Management Studio is using the Open Table/Open View functionality for tables or views. The change type drop down is disabled in Open Table because we don't allow the Visual Studio Query Designer (which is displaying the query) to change the query type for Open Table. In Visual Studio, this restriction is lifted for Query Designer documents.

You can do what you want to do by creating a new query (click the New Query button), typing some text (say, "select"), highlighting the text you typed, right-clicking to bring up a context menu, and selecting "Design Query in Editor." In the Query Designer dialog that appears, you can right click in the upper pane and add tables. You can also right click and change the query type from the context menu.|||I see,Thank you for your Reply

How to change Query Timeout?

Greetings

I have encountered the following problem:

I currently develop an application for my company that actually uses rather long queries, with many records.

I have a particular query (Written using SQL string inside the .NET application rather than Stored proceedures),that needs to run in 2 databases (both SQL Server):

The first one is a test database that we use when in developing time quota to test our data

The second one is the real thing a data base that contains lots of records.

When criteria are placed in the query, it returs few records in both the databases , but if no criteria are placed (So it fetches all the records..) In the test Database works ok, but in the real one it "jams" till 30 seconds pass and I get a time out message...

I tried to change the Query time out time from inside the SQL Server from

Tools/Options/Advanced

but it doesn't seem to work out... it still times out after 30 secs

Any Ideas?

Thanx in advance :DCould it be that this is not a SQL problem but an ADO-ADO.NET problem, i'm sure the default commandtimeout for command objects in ADO-ADO.NET is 30 seconds if not specified, specify 0 for unlimited timeouts and a value in seconds if you want different from the default.

I'd go for a 45 seconds property on the commandtimeout property...

regards,
J.

P.S. If i'm off base here I appologise, this is my first post, total newb...|||Thanks a lot for the advise Dreamweaver, but I need to specify that I tested the queries from inside the SQL Server enterprise Manager creating two new Views (One in each separate Data Base) and pasting in their SQL section the SQL string that I "Pinched off/Copied " from the debugger of the .NET just before it is fed to the adapter...

So I have side by side two new viewes with the exactly same SQL, but belonging to two different data bases...

So the problem arises through the SQL server...

Any more Ideas guys?...

Thanks!. :D|||I've just been looking at the settings on a server I am looking after. Surprisingly the timeout properties in Tools/Options/Advanced differ from right clicking the server and selecting properties and then looking at the bottom part of the connection tab, on this server it has;

0 in Tools/Options/Advanced

and

600 in Server Properties/Connection Tab

I'd have a look in right click Server/Properties/Connection Tab and see if that says 30,

regards,
J.|||first set sp_configure to display advanced options
execute reconfigure with override to force a "LIVE" change
then set remote query timeout to an appropriate value.
run reconfigure with override again.

USE master
EXEC sp_configure 'show advanced option', '1'
/*
Here is the message:
Configuration option 'show advanced options' changed from 0 to 1.
Run the RECONFIGURE command to install.
*/

RECONFIGURE with override
EXEC sp_configure

--XXXX change to query timeout value (example '800')
sp_configure 'remote Query Timeout', 'XXXX'

:eek: I was so tired at the time i wrote this that i lost myself in coloring the code in the message posting areasql

How to change query timeout?

I'm reporting from a web service that takes so long to return that Reporting
Services times out... how can I increase the timeout value when querying for
data?
TIA - ekkisDont try to increase the timeout, instead optimize your query or use stored
proc.
Amarnath
"ekkis" wrote:
> I'm reporting from a web service that takes so long to return that Reporting
> Services times out... how can I increase the timeout value when querying for
> data?
> TIA - ekkis|||perhaps I didn't explain myself correctly. I am reporting from a web service
so there are no stored procedures involved and the "query" is simply the
request to fetch data from the web service.
I have no control over the foreign server so I need to increase the timeout
value. How can I do that?

how to change query that runs report programmatically

I have a report that will display certain records based on the user that logs in. I need to be able to change the query the report uses programmatically. I havent had any luck trying to find how to do this online. If anyone can help me that would be great.
--
Posted using Wimdows.net NntpNews Component -
Post Made from http://www.SqlJunkies.com/newsgroups Our newsgroup engine supports Post Alerts, Ratings, and Searching.Please look into BOL for "Using Dynamic Queries"
--
This posting is provided "AS IS" with no warranties, and confers no rights.
"SqlJunkies User" <User@.-NOSPAM-SqlJunkies.com> wrote in message
news:OtGrybSkEHA.2668@.TK2MSFTNGP10.phx.gbl...
>I have a report that will display certain records based on the user that
>logs in. I need to be able to change the query the report uses
>programmatically. I havent had any luck trying to find how to do this
>online. If anyone can help me that would be great.
>
> --
> Posted using Wimdows.net NntpNews Component -
> Post Made from http://www.SqlJunkies.com/newsgroups Our newsgroup engine
> supports Post Alerts, Ratings, and Searching.

Friday, March 23, 2012

How to change MM/DD/YYYY format to DD/MM/YYYY format by using SQL query.

I have a database table named EMP and I have a column named
DOB(datetime) .I want to retrieve just the MM/DD/YYYY part by using
the CONVERT command.And also I need to change the MM/DD/YYYY to DD/MM/
YYYY format by using the CONVERT command by SQL query.What is the
solution ?
Thank you.
Amritendu Paul
Hello,
For mm/dd/yyyy
Select CONVERT(CHAR(10),columns_name,101) from Table_name
For DD/MM/YY
Select CONVERT(CHAR(10),columns_name,103) from Table_name
Thanks
Hari
<amripaul@.gmail.com> wrote in message
news:1181557806.349855.6210@.x35g2000prf.googlegrou ps.com...
>I have a database table named EMP and I have a column named
> DOB(datetime) .I want to retrieve just the MM/DD/YYYY part by using
> the CONVERT command.And also I need to change the MM/DD/YYYY to DD/MM/
> YYYY format by using the CONVERT command by SQL query.What is the
> solution ?
> Thank you.
> Amritendu Paul
>
|||Thanx for your help.

Monday, March 19, 2012

How to cast the value in C# resulted from max() command in SQL Server Developer

Could anyone help of how to cast the value in C# resulted from max() command. To complicate the matter, from the query result I see in the Microsoft SQL Server Management Studio, if there are records the value is number. But if there are no records, the value is NULL. How do I handle these two possible different conditions?

I have tried:

- stringtest = (string)reader["MaxOrderID"];

- inttest = Convert.ToInt32((string)reader["MaxOrderID"]);

- stringtest = Convert.ToInt32(reader["MaxOrderID"]).ToString();

all failed. And what do I do if the value is NULL. And also how do I do to cope with these two different possible conditions?

For example, I have the following code:

command.CommandText ="Select max(OrderID) as 'MaxOrderID' from [Order]";command.CommandType =CommandType.Text;

command.Connection = conn;

command.Connection.Open();

reader = command.ExecuteReader();

reader.Read();

? orderID = ?reader["MaxOrderID"];

Select MAX(ISNULL(OrderID,0) as MaxOrderID from [Order] try this statment and retest your three statments again...

- stringtest = (string)reader["MaxOrderID"];

- inttest = Convert.ToInt32((string)reader["MaxOrderID"]);

- stringtest = Convert.ToInt32(reader["MaxOrderID"]).ToString();

|||

I executedSelect MAX(ISNULL(OrderID,0)) as MaxOrderID from [Order] , but the value is still NULL, when the table has no records.

I can see that it should be 0.

|||

hi dedyandy,

dedyandy:

I executedSelect MAX(ISNULL(OrderID,0)) as MaxOrderID from [Order] , but the value is still NULL, when the table has no records.

what you are getting is correct, max will return value if there's any record in table else it wont return anything i.e. its a null. you can either use 1 as default value in case there are no records or in case you've procedure then you can check something like

if @.@.Rowcount = 0 Select 1 as 'MaxOrderID'

thanks,

satish.

|||

Thanks Satish. Yes, I will use Count function first. If there are records, I will use AVG function, else return 1.

Andy.

|||

cheersYes

thanks,

Satish.

Monday, March 12, 2012

How to capture the sql query

Hi
can someone explain how the profiler get the queries that are fired against the database. This information will be useful for building a customized trace tool.
ThanksRefer to Inside SQL Server book from Kalen Daleney and also you may get better information from MS Support about designing such a tool.

HTH|||look at the sp_trace_xxxxxx stored procedures

how to capture o/p of SELECT .. FOR XML AUTO.

Hi,
Can u please tell me how can i store o/p of following query into a variable
and process it.
"SELECT TOP 1 FIRSTNAME, LASTNAME FROM PATIENT FOR XML AUTO"
Thanks
Gopinath M.
"Gopinath Munisifreddy" <Gopinath@.Microsoft.com> wrote in message
news:eaMr75zEEHA.3336@.TK2MSFTNGP12.phx.gbl...
> Hi,
> Can u please tell me how can i store o/p of following query into a
variable
> and process it.
> "SELECT TOP 1 FIRSTNAME, LASTNAME FROM PATIENT FOR XML AUTO"
You can't store the results of a for xml query just within SQL. The XML is
created by the provider.
Bryant
|||There are some ugly workarounds using the sp_OA stored procedures.
In SQL Server 2005 (beta2 comming soon, watch this space for nomination
registration), you will be able to do so.
Best regards
Michael
"Bryant Likes" <bryant@.suespammers.org> wrote in message
news:Ogsvi70EEHA.3568@.tk2msftngp13.phx.gbl...
> "Gopinath Munisifreddy" <Gopinath@.Microsoft.com> wrote in message
> news:eaMr75zEEHA.3336@.TK2MSFTNGP12.phx.gbl...
> variable
> You can't store the results of a for xml query just within SQL. The XML is
> created by the provider.
> --
> Bryant
>

Wednesday, March 7, 2012

How to calculate response time.

Hello.
I have a task to do which is as follows:
I have to do an "id query" on a primary key of my db and then calculate the response time of the query.
Task says that i'm able to take screenshots of a graphical view of response time.And as a hint says that there are sql commands that can do such thing.Allthough i've searched the books i have access to and the internet i can't find such thing.I dunno maybe someone more familiar with this stuff can understand what i'm supposed to do.I don't want to give me the whole solution but just if u can tell me where to look.
I don't understand what means "do an id query on primary key 'SMTH' " and i can't find anythin which is related on calculating system response time to execute a query.
Any help is much appreciated.
Thx a lot :)See set statistics statement, set statistics time in particular

Friday, February 24, 2012

How to build this query

Hi,
Please Help me to build this query.

I have got a "User" Table
-------
UserID UserName
-------

1 Tuffy

Another Table "Groups" Table
-------
GroupID GroupName
-------
1 Manager
2 Employee
3 Sales

I have got a "UserGroup" Table HOLDING ID'S as Foreign key.
The data in the TABLE is like this

-------
UserID GroupID
-------
1 1(Manager from "Group" Table
1 2(Employee)
1 3(Sales)
2 2(Employee)
2 3(Sales)
-------

Now when a user logged in The Groups have to be returned as a string that contains pipe separated Group names
for example "Manager|Employee|Sales|"

So if User 1 log in I need something like that
UserID (1)-->"Manager|Employee|Sales|"

Please help me how to write this query.

RegardsTo do this you can do it as -

declare @.roles varchar(100)

SET @.roles = ''

SELECT @.roles = @.roles + '|' + GroupName
FROM UserGroup JOIN GROUPS ON UserGroup.GroupID = Groups.GroupID
Where UserID = @.userID --PAssed userID to the stored procedure

SET @.roles = @.roles + '|'

SELECT @.roles|||...although this will give you a starting and ending pipe.

You might also try:


declare @.roles varchar(200)

SELECT @.roles = COALESCE('|'+G.Groupname, G.GroupName)
FROM UserGroup UG
INNER JOIN GROUPS G ON UG.GroupID = G.GroupID
WHERE UG.UserID = @.userID

SELECT @.Roles


...or simply create @.roles as an output parameter and you won't need to perform that final SELECT.|||Thanks a lot guys. I really appreciate this.
Is there any way of getting the UserID AS WELL

The select query should return

UserID, Groups(Pipe seperated)

The Example I mentioned above, according to that example, the return should be

UserID, Groups
---------
1, Manager|Employee|Sales|
----------------

Many, Many Thanks and Regards|||pjmcb -

How are you going to get one row with all the groupnames with your SQL? I tried it and it just gets the first record.

Am I missing something here?

Thanks,

AP|||No, it was I who was missing something.

Try:


declare @.roles varchar(200)

SELECT @.roles = COALESCE(@.roles+'|'+G.Groupname, G.GroupName)
FROM UserGroup UG
INNER JOIN GROUPS G ON UG.GroupID = G.GroupID
WHERE UG.UserID = @.userID

SELECT @.Roles


With the big difference being in the COALESCE parameter:
COALESCE(@.roles+'|'+G.Groupname, G.GroupName)
instead of
COALESCE('|'+G.Groupname, G.GroupName).

Sorry. My mistake, Was typing quickly. I still haven't tested it yet, but this should work for you...

Sunday, February 19, 2012

How to build dynamic Xquery

Hello

I am trying to use the xml.query() method to output xml. Is there any way of storing the xqueries themselves in the database?

This works:

SELECT Col.query('
<Root>
<Header>
{
for $e in Report/PolicyBatchRef
return $e/PolicyBatchRef
}
</Header>
<NewElement>
{
for $e in Report/PolicyBatchRef/Locations/Location
return $e
}
</NewElement>
</Root>
')
FROM xmltest where id = 1

but this doesn't:

declare @.xquery nvarchar(max)
set @.xquery = '<Root>
<Header>
{
for $e in Report/PolicyBatchRef
return $e/PolicyBatchRef
}
</Header>
<NewElement>
{
for $e in Report/PolicyBatchRef/Locations/Location
return $e
}
</NewElement>
</Root>'
SELECT col.query(@.xquery) from xmltest where id = 1

I get the error

Msg 8172, Level 16, State 1, Line 4
The argument 1 of the xml data type method "query" must be a string literal.

Same thing happens when I store the xquery in the DB.

Any ideas?

Thanks very much

The string argument to the query function must be a string literal, so you cannot pass it in as a parameter. You have a few options:

1. Create UDF's that encapsulate the SELECT and the xquery, and invoke these.

2. Store strings that represent the SELECT and the xquery and invoke them at runtime using sp_executesql

3. store the strings that represent the xquery and combine them with the strings for the SELECT statement, and execute with sp_executesql. This has the most potential for SQL injection since you are constructing SQL dynamically with string concatenation. This method should be used only if the other two ways cannot be used.

|||

You can dynamically create XPath queries using sql variables.

I have successfully used something like

declare @.Date varchar(10)

set @.Date = replace(convert(varchar(10), getdate(), 121), '-', '')

WITH XMLNAMESPACES( 'https://www,somewhere.com/Bureau' AS "Bureau")

SELECT

AggDefaultAmount = convert(varchar(50), ResponseXML.query('sum(/BureauResponse/Bureau:ND07/Bureau:ND07/Bureau:Amount[../Bureau:InformationDate<sql:variable("@.Date")])'))

FROM

DB..testxml WITH (NOLOCK)

Adapt adopt and improve.

|||

Hi,

I need to a have a Store procedure that takes xml as input and it stores in my database tables. Using the nodes() method and value() method, I am able to solve this but only issue I have is these methods take arguments only as string literals. So, I have to hard code the xquery in the SP. I expect to read the xquery from a table and fetch it in a variable within the SP and pass it as the parameter to the Value() and nodes() method.

Please advice.

Sample code I have as below

declare @.xmldoc xml

SET @.xmldoc = '<customer><name>John</name><city>New York</city></customer>'

--This select works

SELECT

T.C.value('name[1]',varchar(50))

T.C.value('city[1]',varchar(50))

FROM @.xmldoc.nodes('/customer') AS T(C)

--But this does not work when I try to specify xquery using a variable as below

declare @.xquery_name varchar(100),@.xquery_city varchar(100), @.xquery_cust varchar(100)

SELECT @.xquery_name = 'name[1]', @.xquery_city = 'city[1]', @.xquery_cust = '/customer'

SELECT

T.C.value(@.xquery_name ,varchar(50))

T.C.value('@.xquery_city',varchar(50))

FROM @.xmldoc.nodes(@.xquery_cust) AS T(C)

Please help me out.

How to build a query into string variable and run it

Hi,

I need to to run an sql query that is stored in string variable, like this:

DECLARE @.wherestr nvarchar

DECLARE @.sqlstring nvarchar

SET @.wherestr = .... some more code to fill @.wherestr

SET @.sqlstring =

'SELECT @.tgid = tgid '+

' FROM target_groups '+

' WHERE '+@.wherestr

But when I call this command using sp_executesql:

EXEC sp_executesql @.SQLString

I recieve following error: "Only functions and extended stored procedures can be executed from within a function."

Is there any possibility to run the command that is stored in some string (nvarchar) variable inside the function?

Note: I'm using SQL Server 2005 Express, Management Studio

thanks for any help

Jiri Matejka

Jiri,

I don't see where you are trying to declare any function.

You can use

EXEC( @.sqlstring)

I am also not sure what you get when you declare something as "nvarchar". Perhaps just "nvarchar(1)". So maybe you want "nvarchar(8000)" or something like that. I have seen others use "nvarchar(max)", which I think is related to some "max" value used when setting up the SQL Server software.

Here is what MS documentation says about "nvarchar" without the size declaration:

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

When n is not specified in a data definition or variable declaration statement, the default length is 1.

The MS terminology for this is DYNAMIC SQL. You can search this forum for it, as well as Microsoft documentation. There are some excellent internet articles with caveats concerning the use of DYNAMIC SQL. You will find links to these in various posts in this forum.

HTH.

Dan

|||

The function I wrote about is something like this

CREATE FUNCTION [dbo].[GetTargetGroup]
(
@.sex int, @.age int
)
RETURNS int
AS
BEGIN
DECLARE @.wherestr nvarchar(255)
SET @.wherestr=@.sexstr+' AND '+@.agecatstr

DECLARE @.sqlstring nvarchar(255)

some more code here ...


SET @.sqlstring = 'SELECT @.tgid = tgid '+
' FROM target_groups '+
' WHERE '+@.wherestr

EXEC sp_executesql @.SQLString

IF @.tgid IS NULL
SET @.tgid=-1

RETURN @.tgid
END

There is no problem with nvarchar, I use it like "nvarchar(255)", I've just shortened the code to be more readable.

Thanks for your help, but when I call EXEC @.SQLstring, that it causes error of "

Could not find stored procedure 'SELECT @.tgid = tgid FROM target_groups WHERE sex=2 AND agecat=32'". So it looks like if EXEC wants to run stored procedure, not given command. But your reference to "DYNAMIC SQL" is a good hint. I'll check it out.

Jiri Matejka


|||

You may not be able to use EXEC(@.SQLString) inside of a function. (But I seem to recall instances where I do just that.)

I think you also need some "N" in front of your strings you are placing in your NVARCHAR variables, as shown in http://msdn2.microsoft.com/en-us/library/ms188001.aspx .

I hope that will work for you. I don't see anything wrong with the SQL statement.

Dan

|||

You cant use dynamic SQL (sp_executesql or Exec ()) on function.

Change your logic to SP.

Possible Alternative,

Create Temp Table on calling proc

Insert data on Callable Proc on the Created Temp table

After the calling use the temp table on your query.

Create Temp table on calling proc

Insert the callable Proc output in Temp table

Use it on your rest of code.

|||i think its not possible cannot use sp_executesql inside a function

what you can do is try to convert your function into a procedure

Code Snippet


CREATE PROCEDURE [dbo].[GetTargetGroup]
(
@.sex int, @.age int
)
AS

DECLARE @.wherestr nvarchar(255)
SET @.wherestr=@.sexstr+' AND '+@.agecatstr

DECLARE @.sqlstring nvarchar(255)
some more code here ...

SET @.sqlstring = 'SELECT ISNULL(tgid,-1) AS tgid '+
' FROM target_groups '+
' WHERE '+@.wherestr
EXEC sp_executesql @.SQLString
GO


you can get your result by

Code Snippet

INSERT

INTO #TGIDResult

EXEC GetTargetGroup @.theSex, @.theAge


SELECT @.tgid = tgid

FROM #TGIDResult


DROP TABLE #TGIDResult




|||

The issue with this technique is that the @.SQLString executes in a separate scope. Here's how you can pass results from the @.SQLString back to your code:

DECLARE @.wherestr varchar(8000) --in SQL 2005, you may use varchar(max)

DECLARE @.sqlstring varchar(8000)

declare @.tgid bigint

--Create a temp table to hold results: in 2005, you can use @.Table rather than #Table if you prefer

select @.tgid as TG_ID into #TGID where 1 = 2

SET @.wherestr = .... some more code to fill @.wherestr

SET @.sqlstring =

'SELECT @.tgid = tgid '+

' FROM target_groups '+

' WHERE ' + @.wherestr

insert into #TGID

exec(@.SQLString)

select * from #TGID

drop table #TGID

How to browse INFORMATION_SCHEMA in Enterprise Manager

Dear all,
I try to (select * from information_schema.columns). It
works ok in query analyzer. But how can I access the information_schema
tables in Enterprise Manager? I try to browse all database, but I
cannot located where is information_schema located in? i.e. Which
database the information_schema is located in that I can browse in
Enterprise Manager?
ThanksI assume you are on 2000? These views only physically exists in the master d
atabase, so unless it is
master you want to look at, EM won't work. Use Query Analyzer and type your
queries instead.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"hon123456" <peterhon321@.yahoo.com.hk> wrote in message
news:1145342246.110319.286500@.u72g2000cwu.googlegroups.com...
> Dear all,
> I try to (select * from information_schema.columns). It
> works ok in query analyzer. But how can I access the information_schema
> tables in Enterprise Manager? I try to browse all database, but I
> cannot located where is information_schema located in? i.e. Which
> database the information_schema is located in that I can browse in
> Enterprise Manager?
> Thanks
>