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

Wednesday, March 28, 2012

How to remove Duplicated data in SQL Table?

Hi

I want to know, how to remove duplicated data in Sql Table using a SQL query? Im using SQL Management Studio Express Edition to connect to database.

Your help will be highly appreciated.

See this thread: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1425992&SiteID=1

Or these articles:


Duplicates –Delete
http://www.sql-server-performance.com/rd_delete_duplicates.asp


Duplicates –Find
http://www.aspfaq.com/2431


Duplicates –
How do I remove duplicates from a table?
http://databases.aspfaq.com/database/how-do-i-remove-duplicates-from-a-table.html


Duplicates –
How to remove duplicate rows from a table in SQL Server
http://support.microsoft.com/?id=139444

Monday, March 26, 2012

How to Remove '-' from QAA -

Can someone help me with a query that removes the '-' from
as string QAA -
ThanksDo you mean something like this:
Select Left('QAA-',3)
"Disney" <Disney@.discussions.microsoft.com> wrote in message
news:FAEFEC69-13FE-43E4-A24E-1EB170CA3445@.microsoft.com...
> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>|||replace('QAA -', '-', '')
rtrim(replace('QAA -', '-', ''))
to get rid of any trailing spaces.
"Disney" <Disney@.discussions.microsoft.com> wrote in message
news:FAEFEC69-13FE-43E4-A24E-1EB170CA3445@.microsoft.com...
> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>|||hi
select left('qaa-',3)
--
thanks,
Jose de Jesus Jr. Mcp,Mcdba
Data Architect
Sykes Asia (Manila philippines)
MCP #2324787
"Disney" wrote:

> Can someone help me with a query that removes the '-' from
> as string QAA -
>
> Thanks
>sql

How to remotely start SQL Server instance?

When you connect to SQL Server instance using SQL Query Analyser there is
"Start SQL Server if it is stopped" option. Is it possible to remotely
start stopped SQL Server instance from my custom application? How?You can use DMO, SMO, or WMI to remotely start the service, google for
more information on this topics like here:
http://www.devx.com/vb2themax/Tip/18459
HTH, Jens Suessmeyer.

Friday, March 23, 2012

How to reference different databases on different servers in one query

Hi,

I'm a novice to SQL Server, though I have some experience in Access.

My problem is this:

I have a table on my local database that I want to insert into a remove database on a different server

What are the steps neccessary?

My local server name is 'HOME\SQLEXPRESS' Local database: 'MyDBTest', table name: 'dbo.Courses' (the fields are: ID, CourseName, TeacherID)|||Take a look in Books On Line at a topic called Linked Servers. Although I am not 100% sure that they are supported in Express|||Using linked servers (first create it using te linked server procedures for that) you can issue this query:

SELECT *
FROM [Linkedservername].[ku.univ].dbo.Courses

HTH, Jens Suessmeyer,

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

I think I'm not using the right syntax

I've created the linked server by:

sp_addlinkedserver @.server='REMOTESRV', @.provider='SQLOLEDB',@.srvproduct='',@.datasrc='129.113.271.58\ku.univ'

The log was: Command(s) completed successfully.

I then tried to issue an SQL Statement as you have adviced:

SELECT *

FROM [REMOTESRV].[ku.univ].dbo.Courses

but the log was:

OLE DB provider "SQLNCLI" for linked server "REMOTESRV" returned message "Login timeout expired".

OLE DB provider "SQLNCLI" for linked server "REMOTESRV" returned message "An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.".

Msg 65535, Level 16, State 1, Line 0

SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

I know that the server allows remote connections: when I connect to it using Object browser I can issue INSERT queries - no problem

Maybe I have a problem with syntax

Thanx a lot

|||Check out the 'Linked Servers' topic in the Books Online|||

Hi,

this here:

,@.datasrc='129.113.271.58\ku.univ'

Should be the instance to connect to, so normally this has to be written in the syntax of:

Servername\Instancename,Portnumber (where as the servername can be exchanged by the ip adress and the portnumber (can be left out if you didn′t choose another one that the default one [or you have SQl Server 2005 at the other end using dynamic port and installed the SQL Server Browser]) and the instancename (which can be left out if you choose the default instance on the server.

So in your case for the default port and the default instance, this should be just:

,@.datasrc='129.113.271.58'

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

|||

Hi, Jens

Thanx a lot for helping, I've changed the @.datasrc as you wrote but got a different error this time:

OLE DB provider "SQLNCLI" for linked server "remotesrv2" returned message "Login timeout expired".

OLE DB provider "SQLNCLI" for linked server "remotesrv2" returned message "An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.".

Msg 53, Level 16, State 1, Line 0

Named Pipes Provider: Could not open a connection to SQL Server [53].

I'd really appreciate your help on this one.

Thanx in advance

|||

Other Ideas, anybody?

I'm pretty stuck here, I've read the documentation, did as it said but still grt an error.

Thanx!

|||

http://blogs.msdn.com/sql_protocols/archive/2005/10/22/483684.aspx

HTH

How to reference different databases on different servers in one query

Hi,

I'm a novice to SQL Server, though I have some experience in Access.

My problem is this:

I have a table on my local database that I want to insert into a remove database on a different server

What are the steps neccessary?

My local server name is 'HOME\SQLEXPRESS' Local database: 'MyDBTest', table name: 'dbo.Courses' (the fields are: ID, CourseName, TeacherID)

The remote SQL Server IP is: 129.113.271.58 (I've changed the real IP) The name of the database on this remote server is: 'ku.univ', and the remote table name I would like to update is 'dbo.Courses' (the table has the same fields as the local one).

I use SQL Server Express Edition

Please help!!

Thank you in advance

Michael

Any ideas?

I'm really stuck here - I am able to connect to the remote server and browse the database, but how do I make an INSERT query to the remote table from my local table?

In Access you could just put any table (local and linked) in one query - there has to be a way to do it in SQL Server

Thanx

|||

There are a couple of options for you. You could use BCP to export the table on the local server to a text file, then use the same utility to insert into the remote server. You can also use a linked server.

To setup a linked server run these commands from sqlcmd, replace the appropriate parameters:

exec sp_addlinkedserver 'RemoteServerName', N'SQL Server'
exec sp_addlinkedsrvlogin 'RemoteServerName',@.locallogin=NULL /*any login*/, @.rmtuser = 'remoteusername', @.rmtpassword='rmtpassword'

Then you will be able to run a query such as this when connected to your local server:

insert [remoteserver].[ku.univ].[dbo].[Tableneme] (columns...)

select columns... from localtable

I'm assuming here that the remote server is also SQL Server. If not you'll need to modify the sp_addlinkedserver call to specify the proper connection string.


How to reference a local temporary table in the @query parm of xp_sendmail

Hi,
Can anyone tell me if a local temporary table can be referenced in the @.quer
y
parameter of the extended procedure xp_sendmail and if so, how?
When I execute the following statements in Query Analyzer, I get the error
message provided below.
CREATE TABLE #TestEmailFile (TestEmailRow varchar(500) null)
INSERT INTO #TestEmailFile VALUES( 'Hello')
EXEC master.dbo.xp_sendmail @.recipients = 'EmailAddress',
@.query = 'SELECT * FROM #TestEmailFile',
@.subject = 'You have mail',
@.message = 'See attachment',
@.attach_results = 'TRUE',
@.width = 500
ODBC error 208 (42S02) Invalid object name '#TestEmailFile'.
Please help!
Message posted via webservertalk.com
http://www.webservertalk.com/Uwe/Forum...amming/200602/1The sendmail executes in a different execution context than the other
connection. If you can guarantee > 1 connection will execute the statement,
then you can use a global temp table (## prefix). You could implement a
locking mechanism using app locks or a semaphore table if you had too, but a
better way to go would be to create a permanent table instead of a temp
table, include the spid in the primary key and everything should work better
(assuming the structure of the table is stable:
use db
go
create table dbo.testEmailFile
(
spid int,
key int,
otherCols int
)
Then
delete from dbo.testEmailFile where spid = @.@.spid --just in case something
fails
--and second delete doesnt happen
insert into dbo.testEmailFile
select @.@.spid, etc
EXEC master.dbo.xp_sendmail @.recipients = 'EmailAddress',
@.query = 'SELECT * FROM db.dbo.TestEmailFile',
@.subject = 'You have mail',
@.message = 'See attachment',
@.attach_results = 'TRUE',
@.width = 500
delete from dbo.testEmailFile where spid = @.@.spid --good data steward
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"Cismail via webservertalk.com" <u14416@.uwe> wrote in message
news:5c5275146e3b0@.uwe...
> Hi,
> Can anyone tell me if a local temporary table can be referenced in the
> @.query
> parameter of the extended procedure xp_sendmail and if so, how?
> When I execute the following statements in Query Analyzer, I get the error
> message provided below.
> CREATE TABLE #TestEmailFile (TestEmailRow varchar(500) null)
> INSERT INTO #TestEmailFile VALUES( 'Hello')
> EXEC master.dbo.xp_sendmail @.recipients = 'EmailAddress',
> @.query = 'SELECT * FROM #TestEmailFile',
> @.subject = 'You have mail',
> @.message = 'See attachment',
> @.attach_results = 'TRUE',
> @.width = 500
>
> ODBC error 208 (42S02) Invalid object name '#TestEmailFile'.
> Please help!
> --
> Message posted via webservertalk.com
> http://www.webservertalk.com/Uwe/Forum...amming/200602/1|||Very helpful. Thanks indeed!
Louis Davidson wrote:
>The sendmail executes in a different execution context than the other
>connection. If you can guarantee > 1 connection will execute the statement
,
>then you can use a global temp table (## prefix). You could implement a
>locking mechanism using app locks or a semaphore table if you had too, but
a
>better way to go would be to create a permanent table instead of a temp
>table, include the spid in the primary key and everything should work bette
r
>(assuming the structure of the table is stable:
>use db
>go
>create table dbo.testEmailFile
>(
> spid int,
> key int,
> otherCols int
> )
>Then
>delete from dbo.testEmailFile where spid = @.@.spid --just in case something
>fails
> --and second delete doesnt happen
>insert into dbo.testEmailFile
>select @.@.spid, etc
>EXEC master.dbo.xp_sendmail @.recipients = 'EmailAddress',
> @.query = 'SELECT * FROM db.dbo.TestEmailFile',
> @.subject = 'You have mail',
> @.message = 'See attachment',
> @.attach_results = 'TRUE',
> @.width = 500
>delete from dbo.testEmailFile where spid = @.@.spid --good data steward
>----
-
>Louis Davidson - http://spaces.msn.com/members/drsql/
>SQL Server MVP
>"Arguments are to be avoided: they are always vulgar and often convincing."
>(Oscar Wilde)
>
>[quoted text clipped - 17 lines]
Message posted via webservertalk.com
http://www.webservertalk.com/Uwe/Forum...amming/200602/1

How to refer to Custom function in a query

I want to be able to refer to a custom function in a query
The Function is defined in the report proprties "Code" tab as follows:
public shared function MyCustomer as String
Return "ALFKI"
end function
I have tried different query formats, and I currently have:
="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
"'"
I am using the Northwind database as an example
Though the code compiles, I am unable to refer to any of the fields in
"customers"
I know there are other ways to accomplish this. What I am interested in
is how to refer to user defined code in QueriesYou might be able to pull a field list first with simply
SELECT * FROM customers
and then change the SQL to include the code. You might want to try the
latter using View Code and see of that gets around the auto-population of
fields step.
--
Cheers,
'(' Jeff A. Stucker
\
Business Intelligence
www.criadvantage.com
---
"cab0san" <cabosan@.gmail.com> wrote in message
news:1109783555.987331.113460@.g14g2000cwa.googlegroups.com...
>I want to be able to refer to a custom function in a query
> The Function is defined in the report proprties "Code" tab as follows:
> public shared function MyCustomer as String
> Return "ALFKI"
> end function
> I have tried different query formats, and I currently have:
> ="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
> "'"
> I am using the Northwind database as an example
> Though the code compiles, I am unable to refer to any of the fields in
> "customers"
> I know there are other ways to accomplish this. What I am interested in
> is how to refer to user defined code in Queries
>|||Thanks, that works. A bit "klugy" but it works!
So, I set my query to
select * from customers, then execute the query, then click another
tab, causing the field list to populate, then switch back to the data
tab and change it to
="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
"'"
Behind the scenes that is accomplishing the step of adding the dataset
definition to my RDL|||I'm glad it's working.
I found that editing directly in the data tab works fine until you have a
complex SQL statement that uses its own declared variables (which for SQL
Server look similar to parameters: @.ParmName). When you add parameters
manually to the dataset, sometimes the data tab editing blows away those
manually entered parameters. That's when I use Bruce's suggestion to edit
SQL using View Code.
--
Cheers,
'(' Jeff A. Stucker
\
Business Intelligence
www.criadvantage.com
---
"cab0san" <cabosan@.gmail.com> wrote in message
news:1109862516.895060.241340@.l41g2000cwc.googlegroups.com...
> Thanks, that works. A bit "klugy" but it works!
> So, I set my query to
> select * from customers, then execute the query, then click another
> tab, causing the field list to populate, then switch back to the data
> tab and change it to
> ="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
> "'"
> Behind the scenes that is accomplishing the step of adding the dataset
> definition to my RDL
>|||I have a similar issue however I am using a DB2 stored procedure so I dont
have the option to manipulate the sql. I was trying to put a translation on
the parameters list somehow and that doesnt seem to work although in the
Hitchhikers Guide it states that you can use and expression anywhere you have
the opportunity presented by <expression> or Fx ... which I see as an option
on the datasource parameters tab. I need to translate the client I receive
in as a parameter into a different value.
On the dataset parameters tab I have Parameter Name PM_Client_Code and the
value is =Code.TranslateClient(Parameters!PM_CLIENT_CODE.Value)
The function TranslateClient is this:
Function TranslateClient(ByVal clientnum As String) As String
TranslateClient = "ABC"
End Function
It doesnt work. Although the code works in vb .net just fine.
"cab0san" wrote:
> Thanks, that works. A bit "klugy" but it works!
> So, I set my query to
> select * from customers, then execute the query, then click another
> tab, causing the field list to populate, then switch back to the data
> tab and change it to
> ="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
> "'"
> Behind the scenes that is accomplishing the step of adding the dataset
> definition to my RDL
>|||That looks good to me and should work. I suggest creating a report just with
your parameter and a textbox and assign this expression to the textbox (so
you can see what happens). Make sure that your parameter is exactly the name
you have here, the parameter is case sensitive.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"MJ Taft" <MJTaft@.discussions.microsoft.com> wrote in message
news:0EF45D79-4C8A-4B99-9D5A-30610FFB1F9D@.microsoft.com...
> I have a similar issue however I am using a DB2 stored procedure so I dont
> have the option to manipulate the sql. I was trying to put a translation
on
> the parameters list somehow and that doesnt seem to work although in the
> Hitchhikers Guide it states that you can use and expression anywhere you
have
> the opportunity presented by <expression> or Fx ... which I see as an
option
> on the datasource parameters tab. I need to translate the client I
receive
> in as a parameter into a different value.
> On the dataset parameters tab I have Parameter Name PM_Client_Code and the
> value is =Code.TranslateClient(Parameters!PM_CLIENT_CODE.Value)
> The function TranslateClient is this:
> Function TranslateClient(ByVal clientnum As String) As String
> TranslateClient = "ABC"
> End Function
> It doesnt work. Although the code works in vb .net just fine.
> "cab0san" wrote:
> > Thanks, that works. A bit "klugy" but it works!
> >
> > So, I set my query to
> >
> > select * from customers, then execute the query, then click another
> > tab, causing the field list to populate, then switch back to the data
> > tab and change it to
> > ="SELECT * FROM customers where CustomerID='" + Code.MyCustomer() +
> > "'"
> > Behind the scenes that is accomplishing the step of adding the dataset
> > definition to my RDL
> >
> >

Monday, March 19, 2012

How to recover from mdf file (SQL Server 2000)

Hi,

My database corrupted because when I was running an update query, there is a power failure. After the computer booted, I cannot open the database anymore, it just not responding. Then I stop the sql server service, and tried to rename the .mdf and .ldf. After that it worked normally, but I need the data from the corrupted mdf file, I tried to attach the database but it just hanged. I even tried to attach without the .ldf file but it didn't work either, so I concluded that the problem is with the mdf file.

Is there any way to recover my data ?

Thanks in advance

Regards,

Edwin

Can you rename the mdf,ldf files to their original names and attach them to your SQL Server? (with all SQL Services running)

If that works, try using

DBCC CHECKDB ('DatabaseName' /*,REPAIR_REBUILD*/)
WITH NO_INFOMSGS, ALL_ERRORMSGS, DATA_PURITY

To see what went wrong

A 2nd choice is to restore the mdf,ldf files from a recent backup (if backup exists)

|||

Hi,

We'd tried that but we got no luck. Attaching the file in it's original name didn't work, the computer just hanged, we suspected that the .mdf file corrupted

Unfortunately, we don't have any backup.

Thanks for reply

|||

Can you try this trick:

Create a new 'dummy' database that has the same name as the old database, say 'TEST'

So now you have 2 files: test.mdf and test.ldf files

Stop SQL Server services and delete these files

Copy and rename your corrupted mdf,ldf files in their place

Restart the services and see what error message you get when SQL tries to read from the corrupted files that are now attached to the TEST db.

Then you can start the debugging 'process' based on error number

Cheers

|||Try this undocumented stuff provided by Kevin [MS].

==========
1. Back up the .mdf/.ndf files at first!!!

2. Change the database context to Master and allow updates to system tables:

Use Master
Go
sp_configure 'allow updates', 1
reconfigure with override
Go

3. Set the database in Emergency (bypass recovery) mode:

select * from sysdatabases where name = '<db_name>'
-- note the value of the status column for later use in # 6
begin tran
update sysdatabases set status = 32768 where name = '<db_name>'
-- Verify one row is updated before committing
commit tran

4. Stop and restart SQL server.

5. Call DBCC REBUILD_LOG command to rebuild a "blank" log file based on the
suspected db.
The syntax for DBCC REBUILD_LOG is as follows:

DBCC rebuild_log('<db_name>','<log_filename>')

where <db_name> is the name of the database and <log_filename> is
the physical path to the new log file, not a logical file name. If you
do not
specify the full path, the new log is created in the Windows NT system
root
directory (by default, this is the Winnt\System32 directory).

6. Set the database in single-user mode and run DBCC CHECKDB to validate
physical consistency:

sp_dboption '<db_name>', 'single user', 'true'
DBCC checkdb('<db_name>')
Go
begin tran
update sysdatabases set status = <prior value> where name = '<db_name>'
-- verify one row is updated before committing
commit tran
Go

7. Turn off the updates to system tables by using:

sp_configure 'allow updates', 0
reconfigure with override
Go
============|||

OK.

First off, I don't think I've posted those steps. I've probably posted similar for use in DIRE circumstances (like this one) where there is no backup, and data loss is acceptable.

The procedure above is primarily used for cases where you have only the MDF file and no log.

Attaching the database should not hang the system. It could make it busy for awhile, but not totally hang.

How long did you let the system go before giving up and canceling?

Please look in both the Windows Event Log and in the SQL errorlog files and post any related errors here.

You need to get the database attached to an instance in order to do anything with it. Your best bet is to put the files back in their original locations and just let it run its course. You might try putting the database in emergency mode (using the steps above) before putting the files back in place. Then the database wouldn't run recovery when the instance started up.

You could then run DBCC CHECKDB , and presuming that there are serious problems, you can then re-run the CHECKDB with REPAIR_ALLOW_DATA_LOSS, taking into consideration that the command means what it says: data will be lost.

Monday, March 12, 2012

How to recall column name defined in CASE function

Hello all,

I need to refine a query in which one of the search conditions would depend on the value evaluated from the CASE function in SELECT statement. This returned column is named as "SLA". Now, the problem is I don't know how to recall this column in the WHERE clause as to do refinement. When I code it like SLA = @.Term, SQL Server returned an error: Invalid column name 'SLA'

If anyone knows a solution, please kindly let me know.

Thank you!

Here is the sample code:

ALTER PROCEDURE [dbo].[sp_premium_register]
@.PolicyType AS VARCHAR(10),
@.ReportFrom AS DATETIME,
@.ReportTo AS DATETIME,
@.Business AS VARCHAR(1),
@.Term AS VARCHAR(1)

SELECT
ColumnA,
ColumnB,

SLA =
CASE
WHEN DateDiff(day, P.EffectiveFrom, P.EffectiveTo) > 1 THEN 'L'
WHEN DateDiff(day, P.EffectiveFrom, P.EffectiveTo) <= 1 THEN 'S'
END

FROM DNIssue D
LEFT OUTER JOIN KILRIShare S
ON (D.PolicyNo = S.PolicyNo AND D.PolicyType = S.PolicyType AND D.Origin = S.Origin AND D.EndorsementNo = S.EndrNo AND D.PartyNo = S.RINo)
LEFT OUTER JOIN KILPolicy P
ON (D.PolicyNo = P.PolicyNo AND D.PolicyType = P.PolicyType AND D.Origin = P.Origin AND D.EndorsementNo = P.EndrNo)
LEFT OUTER JOIN v_report_KILDNFund F
ON (D.DebitNote = F.DebitNote)
LEFT OUTER JOIN PolicyProfile R
ON R.Origin = D.Origin AND R.PolicyType = D.PolicyType

WHERE
SLA = @.Term

Order by D.PolicyType, D.DebitNote, D.Origin, D.PolicyNo, D.EndorsementNo, D.EntryDateuse an outer query
SELECT ColumnA
, ColumnB
, SLA
FROM (
SELECT ColumnA
, ColumnB
, SLA =
CASE
WHEN DateDiff(day, P.EffectiveFrom, P.EffectiveTo) > 1
THEN 'L'
else 'S'
END
FROM DNIssue D
LEFT OUTER
JOIN KILRIShare S
ON S.PolicyNo = D.PolicyNo
AND S.PolicyType = D.PolicyType
AND S.Origin = D.Origin
AND S.EndrNo = D.EndorsementNo
AND S.RINo = D.PartyNo
LEFT OUTER
JOIN KILPolicy P
ON P.PolicyNo = D.PolicyNo
AND P.PolicyType = D.PolicyType
AND P.Origin = D.Origin
AND P.EndrNo = D.EndorsementNo
LEFT OUTER
JOIN v_report_KILDNFund F
ON F.DebitNote = D.DebitNote
LEFT OUTER
JOIN PolicyProfile R
ON R.Origin = D.Origin
AND R.PolicyType = D.PolicyType
ORDER
BY D.PolicyType
, D.DebitNote
, D.Origin
, D.PolicyNo
, D.EndorsementNo
, D.EntryDate
) as t
WHERE SLA = @.Term or bite the bullet and code the datediff into the WHERE condition|||you'll have to repeat the case statement in your where clause|||It works! Thank you so much!!!

Friday, March 9, 2012

How to read windows registry thru query ?

Hi
How can I access the windows registry entries from MSSQL Server query analyzer. I am looking for some stored procedures. Are there any system stored procedures ?
ThxExtended procedure xp_regread
USE Master
EXEC xp_regread 'HKEY_LOCAL_MACHINE',
'SOFTWARE\Microsoft\MSSQLServer\Setup',
'SQLPath'

How to read the xml returned by select query with "For XML Auto,Elements"

Hi all,

I am writing a select query which produces huge xml data.Now i want to read that data from my web application a save it as xml file.

How can i do that.

I am using asp.net vb.net.

Check if this post is helpful.

http://forums.asp.net/t/1182514.aspx

how to read the query in store procedure

i wrote a stored procedure here is the code

CREATE Procedure dm_deleteBBPost
(
@.TopicIDnumeric,
@.ForumIDnumeric

)
As
declare @.netCount as int

BEGIN
Select @.netCount=count(*) from tablename where TopicID=@.TopicID

update tablename set TotalTopics=TotalTopics-1,TotalPosts=TotalPosts-@.netCount where ForumID=@.ForumID

Delete From tblBBPosts Where TopicID = @.TopicID
Delete From tblBBTopics Where TopicID =@.TopicID

end
declare @.pr_ForumsToday as varchar

////////// select Top 1 * from tablename order by column name desc
GO

IN that last line one row will be displayed. how can i read one of the field from the query (selct top1 etc)

Quote:

Originally Posted by madhu7sudan

i wrote a stored procedure here is the code

CREATE Procedure dm_deleteBBPost
(
@.TopicIDnumeric,
@.ForumIDnumeric

)
As
declare @.netCount as int

BEGIN
Select @.netCount=count(*) from tablename where TopicID=@.TopicID

update tablename set TotalTopics=TotalTopics-1,TotalPosts=TotalPosts-@.netCount where ForumID=@.ForumID

Delete From tblBBPosts Where TopicID = @.TopicID
Delete From tblBBTopics Where TopicID =@.TopicID

end
declare @.pr_ForumsToday as varchar

////////// select Top 1 * from tablename order by column name desc
GO

IN that last line one row will be displayed. how can i read one of the field from the query (selct top1 etc)


Try this...

SELECT TOP 1 COLUMNNAME FROM TABLENAME ORDER BY COLUMN NAME DESC

Wednesday, March 7, 2012

How to read if an index column is descending

I am reading the index keys through a query and not using sp_helpindex
because I need to make a join on the query.
How can I know if the index column is in descending order
the query i am using is the following:
select sysobjects.name as TableName
, sysindexes.name as IndexName
, sysindexkeys.keyno as Position
, syscolumns.name as FieldName
from sysindexkeys
left outer join sysobjects on sysindexkeys.id = sysobjects.id
left outer join sysindexes on sysindexkeys.id = sysindexes.id and
sysindexkeys.indid = sysindexes.indid
left outer join syscolumns on sysindexkeys.id = syscolumns.id and
sysindexkeys.colid = syscolumns.colid
order by sysobjects.name, sysindexes.name, sysindexkeys.keynoHi
Although you are not using sp_helpindex, you may have noticed that decending
keys are notated by a '(-)' next to the key columns when displaying, checkin
g
out the source for sp_helpindex you will see:
if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
select @.keys = @.keys + '(-)'
Therefore this can be incorporated in your statement:
select o.name as TableName
, i.name as IndexName
, k.keyno as Position
, c.name as FieldName
, CASE WHEN indexkey_property(o.id, i.indid, 1, 'isdescending') = 1) THEN
'Descending'
ELSE 'Ascending'
END AS Direction
from sysindexkeys k
left join sysobjects o on k.id = o.id
left join sysindexes i on k.id = i.id and k.indid = i.indid
left outer join syscolumns c on k.id = c.id and k.colid = c.colid
order by o.name, i.name, k.keyno
John
"Nadim Wakim - Lebanon" wrote:

> I am reading the index keys through a query and not using sp_helpindex
> because I need to make a join on the query.
> How can I know if the index column is in descending order
>
> the query i am using is the following:
> select sysobjects.name as TableName
> , sysindexes.name as IndexName
> , sysindexkeys.keyno as Position
> , syscolumns.name as FieldName
> from sysindexkeys
> left outer join sysobjects on sysindexkeys.id = sysobjects.id
> left outer join sysindexes on sysindexkeys.id = sysindexes.id and
> sysindexkeys.indid = sysindexes.indid
> left outer join syscolumns on sysindexkeys.id = syscolumns.id and
> sysindexkeys.colid = syscolumns.colid
> order by sysobjects.name, sysindexes.name, sysindexkeys.keyno
>
>|||Dear John, although indexkey_property is working in the current db, i need
to use it to query from another db in order to compare indexes between 2
dbs.
if i use:
Select indexkey_property(o.id, i.indid, 1, 'isdescending')
from db1.dbo.sysobjects o
left outer join sysobjects current on ......
, the function returns NULL because it is looking for the id in the current
database.
if i try to use db1.dbo.indexkey_property(), i get an error.
I am trying to compare the indexes structure between a template database and
the database i am connecting to in a query.
"John Bell" <JohnBell@.discussions.microsoft.com> wrote in message
news:9498A7E0-D40B-4D13-A1C2-751EB0B03B8F@.microsoft.com...
> Hi
> Although you are not using sp_helpindex, you may have noticed that
> decending
> keys are notated by a '(-)' next to the key columns when displaying,
> checking
> out the source for sp_helpindex you will see:
> if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
> select @.keys = @.keys + '(-)'
> Therefore this can be incorporated in your statement:
> select o.name as TableName
> , i.name as IndexName
> , k.keyno as Position
> , c.name as FieldName
> , CASE WHEN indexkey_property(o.id, i.indid, 1, 'isdescending') = 1) THEN
> 'Descending'
> ELSE 'Ascending'
> END AS Direction
> from sysindexkeys k
> left join sysobjects o on k.id = o.id
> left join sysindexes i on k.id = i.id and k.indid = i.indid
> left outer join syscolumns c on k.id = c.id and k.colid = c.colid
> order by o.name, i.name, k.keyno
>
> John
> "Nadim Wakim - Lebanon" wrote:
>|||Instead of reinventing the wheel there are lots of inexpensive 3rd party
products out there that do these comparisons for you.
http://www.aspfaq.com/show.asp?id=2209
Some of them (I know Red-Gate does) come with an api to allow you to do
these comparisons programatically.
Andrew J. Kelly SQL MVP
"Nadim Wakim" <nadimlb@.cyberia.net.lb> wrote in message
news:e35REvNEFHA.1264@.TK2MSFTNGP12.phx.gbl...
> Dear John, although indexkey_property is working in the current db, i need
> to use it to query from another db in order to compare indexes between 2
> dbs.
> if i use:
> Select indexkey_property(o.id, i.indid, 1, 'isdescending')
> from db1.dbo.sysobjects o
> left outer join sysobjects current on ......
> , the function returns NULL because it is looking for the id in the
> current database.
> if i try to use db1.dbo.indexkey_property(), i get an error.
> I am trying to compare the indexes structure between a template database
> and the database i am connecting to in a query.
>
>
> "John Bell" <JohnBell@.discussions.microsoft.com> wrote in message
> news:9498A7E0-D40B-4D13-A1C2-751EB0B03B8F@.microsoft.com...
>|||Dear Andrew, i tried 'Red gate' it's very efficient but it doesn't work in
case or replication.
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:eFH6llQEFHA.732@.TK2MSFTNGP12.phx.gbl...
> Instead of reinventing the wheel there are lots of inexpensive 3rd party
> products out there that do these comparisons for you.
> http://www.aspfaq.com/show.asp?id=2209
> Some of them (I know Red-Gate does) come with an api to allow you to do
> these comparisons programatically.
>
> --
> Andrew J. Kelly SQL MVP
>
> "Nadim Wakim" <nadimlb@.cyberia.net.lb> wrote in message
> news:e35REvNEFHA.1264@.TK2MSFTNGP12.phx.gbl...
>|||Hi
You can put your results into a table and then process them
USE TEMPDB
CREATE TABLE [IndexTypes] (
[DBName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[name] [sysname] NOT NULL ,
[id] [int] NOT NULL ,
[indid] [smallint] NOT NULL ,
[Direction] [int] NULL
)
GO
USE DB1
INSERT INTO tempdb..IndexTypes
Select db_name() as DBName, o.name, o.id, i.indid,
indexkey_property(o.id, i.indid, 1, 'isdescending') as Direction
from sysobjects o
JOIN sysindexes i ON o.id = i.id
USE DB2
INSERT INTO tempdb..IndexTypes
Select db_name() as DBName, o.name, o.id, i.indid,
indexkey_property(o.id, i.indid, 1, 'isdescending') as Direction
from sysobjects o
JOIN sysindexes i ON o.id = i.id
SELECT * FROM tempdb..IndexTypes
where name = 'MyTable2'
John
Nadim Wakim wrote:
> Dear Andrew, i tried 'Red gate' it's very efficient but it doesn't
work in
> case or replication.
>
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:eFH6llQEFHA.732@.TK2MSFTNGP12.phx.gbl...
party
to do
db, i
indexes
the
database
that
displaying,
1)
sp_helpindex
and
and

Friday, February 24, 2012

how to quote the tabel?

Hi,
I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
is the network name.
If I put select * from xyz\abc1234.test, it will give me an error msg.
What shall I do?
Thanks a lot!
Michael
On Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
don't x-post
use brackets
select * from [xyz\abc1234].test
Denis the SQL Menace
http://sqlservercode.blogspot.com/
|||On Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
try select * from [xyz\abc1234.test]

how to quote the tabel?

Hi,
I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
is the network name.
If I put select * from xyz\abc1234.test, it will give me an error msg.
What shall I do?
Thanks a lot!
MichaelOn Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
don't x-post
use brackets
select * from [xyz\abc1234].test
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||On Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
try select * from [xyz\abc1234.test]

how to quote the tabel?

Hi,
I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
is the network name.
If I put select * from xyz\abc1234.test, it will give me an error msg.
What shall I do?
Thanks a lot!
MichaelOn Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
don't x-post
use brackets
select * from [xyz\abc1234].test
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||On Apr 12, 10:09 am, "Michael" <michae...@.gmail.com> wrote:
> Hi,
> I have table name like 'xyz\abc1234.test' in SQL Query Analyzer. xyz
> is the network name.
> If I put select * from xyz\abc1234.test, it will give me an error msg.
> What shall I do?
> Thanks a lot!
> Michael
try select * from [xyz\abc1234.test]

how to quickly learn the syntax of SQL?


Hi, All:

I know oracle SQL, now I need to do a lot of SQL query on Microsoft SQLSERVER, can any one point out any place that I can find out the syntax of SQLserver SQL statement? Since this is just a short term assignment, so I don't want to buy a book, just hoping I can learn something quickly from online. I don't need learn anything deep, just need to know some simple syntax so I can do join, count, concatenate, min(), max(), sum () etc.
thanks in advance.Books Online, the definitive source for information about SQL Server and T-SQL, is available online here, to for free download here.|||

You will be suprised that for the standard things like joining and concatenating, SQL Server support most things the ANSI standard which lets you change your SQL strings easily. For special things like system functions you will need the appropiate TSQL equivalent but for ANSI joining like *= you can do a "soft-migration" to SQL Server. (And in addition you won′t need the dual table anymore :-) ) :-D

Jens K. Suessmeyer.

http://www.sqlserver2005.de

|||
Hi, Thanks for all of your replies.

how to quick query duplicate records?

any idea?

quick query duplicate records (speicifed fields.value are same) using T-SQL?

depends on how many columns you've got in the table but as an example:

say you have a table called Customer with one column called CustomerID then this simple query will tell you.

SELECT CustomerID, COUNT(*)

FROM Customer

GROUP BY CustomerID

HAVING COUNT(*) > 1

ORDER BY 2 DESC

|||

Thanks your reply what i want is

display duplicate records depends on multi-column

regards

|||

just add the extra columns in to the SELECT and GROUP BY clauses and it will work for multiple columns.

even better, can u post an example of the data that you are wanting to look for duplicates in?

|||

At the same time if you table own identity field you could use another query. Keeping on mind identity value you drop the one own less value.

I'm sorry but I don't have that query

|||

Because i want to remove duplicate records,so have to display first i think

I found an article

http://www.sqlservercentral.com/columnists/chawkins/dedupingdatainsqlserver2005.asp

I think it's cool, sharing

How to query?

In the following query, @.CusVenRefLike is a string entered by user, it is by default equal to '%' so that the query return all string when user enter nothing.

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE Customer.CustomerRef LIKE @.CusVenRefLike

I find that the resulting dataset contain ONLY rows that Voucher.CustomerID<>-1. The reason is that when Voucher.CustomerID= -1, Customer.CustomerRef=NULL which is not included in Customer.CustomerRef LIKE '%' filter.

How can I include those row with Voucher.CustomerID=-1?

Thanks

You need to add additional constraints to your query, depending on exactly how you want it to work.

A simple approach is to use Coalesce(CustomerRef, '' ) to force the null into an empty string. This allows the match to procede. In fact, if there is no special meaning to the CustomerRef being NULL you might want to add a default to the column.

If you want to include nulls in any search, then add Or CustomerRef Is Null to the Where clause. You could also add Or (CustomerRef Is Null and @.CusVenRefLike = '%').

|||

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE Customer.CustomerRef LIKE @.CusVenRefLike

or Customer.CustomerRef is null

|||

Can do it as this as well..

SELECT Voucher.VoucherID, Voucher.VoucherRef, Customer.CustomerRef
FROM Voucher
LEFT Join Customer on Voucher.CustomerID=Customer.CustomerID
WHERE isnull(Customer.CustomerRef ,'') LIKE @.CusVenRefLike

How to Query... Please help

hi friends,

I have a table whose one field is 'monthname' containing month names. I want to get these month names as field values with an SQLQry. no Stored procedures or functions can be used.

Normal Result: (Select monthname Month,Count(ID) Count From TestData Group By Monthname)

MonthCountJan2Feb7Mar3Apr4May5Jun2Jul2Aug4Sept5Oct6Nov4Dec4

My Required Format:

IDJanFebMarAprMayJunJulAugSeptOctNovDec1231234888665555

(this month name is just an example, it can be anything. like year or Flight Name. I mean i cant hard code like 'Select * From TestData where monthName = 'Jan'')

Got me...?

Thanking,

:)

Search these forums for pivot. Or advanced search where I say something about pivot in this forum.