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

Friday, March 30, 2012

How to format numbers in SQL Query

any body have an idea abou how to wirte a function for formating a numeric field.
Ex: In my table the TotalAmout is a numeric field. if i use (Select TotalAmount from Table1) then query will return numbers like

Totalamount
-------
12232.88
23233.22
23559.99
32434.99

but i want he result like comma separated format
like

12,232.88
23,233.22
23,559.99
32,434.99Create the below function and use it as said below.

/*This function is only for thousand separator for numbers with length 5 or 4*/
CREATE FUNCTION DBO.SEPARATETHOUSANDNUM
(
@.STRVALUE VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN

DECLARE @.STRRETURNVALUE VARCHAR(8000)
SELECT @.STRRETURNVALUE = CASE LEN(@.STRVALUE)
WHEN 5 THEN LEFT(@.STRVALUE,2)+ ','+ RIGHT(@.STRVALUE,3)
WHEN 4 THEN LEFT(@.STRVALUE,1)+ ','+ RIGHT(@.STRVALUE,3)
ELSE @.STRVALUE END
RETURN @.STRRETURNVALUE
END

SELECT DBO.SEPAREATENUMBERS(23565) AS CHANGEDCOLUMN

gives 23,565

SELECT DBO.SEPAREATENUMBERS(2365) AS CHANGEDCOLUMN

gives 2,365

So use
Select DBO.SEPARATETHOUSANDNUM(TotalAmount) from Table1

Quote:

Originally Posted by sukeshchand

any body have an idea abou how to wirte a function for formating a numeric field.
Ex: In my table the TotalAmout is a numeric field. if i use (Select TotalAmount from Table1) then query will return numbers like

Totalamount
-------
12232.88
23233.22
23559.99
32434.99

but i want he result like comma separated format
like

12,232.88
23,233.22
23,559.99
32,434.99

|||I got an another easy solution for that and no need for any functions

like this

select convert(varchar(50),convert(momey,TotalAmount),1) from BillMaser|||

Quote:

Originally Posted by sukeshchand

I got an another easy solution for that and no need for any functions

like this

select convert(varchar(50),convert(momey,TotalAmount),1) from BillMaser


Excellent! Thanks for posting the solution!|||

Quote:

Originally Posted by sukeshchand

I got an another easy solution for that and no need for any functions

like this

select convert(varchar(50),convert(money,TotalAmount),1) from BillMaser


i'm using this query, it works, but my problem now is that this query automatically rounds to 2 decimal places.

ex.
1200.114 = 1,200.11

is there a query that formats the result but does not round the decimals?|||

Quote:

Originally Posted by mjv

i'm using this query, it works, but my problem now is that this query automatically rounds to 2 decimal places.

ex.
1200.114 = 1,200.11

is there a query that formats the result but does not round the decimals?


try adding precision on your convert function.

actually, although this is feasible in the database/back-end, i believe this can be better be handled in the front-end.

how to format in to dd/mm/yyyy ?

hi all,

i have table field name call

Start_date varchar(16)

when i select data from that filed values it gives me

Eg:

select Start_date from Customer

20011224 00:00:0
20011004 00:00:0

but i want to convert this data in to dd/mm/yyyy format ?

like ! 24/12/2001

04/10/2001

how do i do this task ?


regards

sujithf

create table #format (

start_Date_time varchar(16)

)

insert into #format values('20011224 00:00:0')

select convert(varchar(16), cast(start_date_time as datetime), 103) from #format

--103 is a British/French date format "dd/mm/yyyy"

|||

thanks very much.....

regards

sujithf

How to format in SSMS?

How can I format a query in SSMS so it does not look like this:

sELecT * fRoM CusTomERs

Currently SSMS doesn't have any tools to format queries except of query designer and Ctrl+Shift+U or Ctrl+Shift+L.|||I use promptsql.com for intellisense, which allow me to pick table and column names from a drop down. It integrates with SSMS and QA. -- Tibor Karaszi, SQL Server MVP http://www.karaszi.com/sqlserver/default.asp http://www.solidqualitylearning.com/ Blog: http://solidqualitylearning.com/blogs/tibor/ wrote in message news:da5be6aa-131a-4585-92c5-5114765096f7@.discussions.microsoft.com...
> Currently SSMS doesn't have any tools to format queries except of query
> designer and Ctrl+Shift+U or Ctrl+Shift+L.
>|||

Somebdy wake me from this bad dream!

Yes I have tried promptsql. It is slow and does not format keywords, but is the only intellisense addon that works with SSMS. A much better product is SqlAssist but only works in Visual Studio. VS on the other hand is horrible for working with dbs, so I started cutting and pasting queries into SSMS.

Shame on Microsoft for all this marketting hoopla and they basically put out archaic software that is stuck in the 70s.

|||FWIW the latest release of PromptSQL will auto-uppercase keywords, and has new caching features which should make it faster.sql

How to format in SSMS?

How can I format a query in SSMS so it does not look like this:

sELecT * fRoM CusTomERs

Currently SSMS doesn't have any tools to format queries except of query designer and Ctrl+Shift+U or Ctrl+Shift+L.|||I use promptsql.com for intellisense, which allow me to pick table and column names from a drop down. It integrates with SSMS and QA. -- Tibor Karaszi, SQL Server MVP http://www.karaszi.com/sqlserver/default.asp http://www.solidqualitylearning.com/ Blog: http://solidqualitylearning.com/blogs/tibor/ wrote in message news:da5be6aa-131a-4585-92c5-5114765096f7@.discussions.microsoft.com...
> Currently SSMS doesn't have any tools to format queries except of query
> designer and Ctrl+Shift+U or Ctrl+Shift+L.
>|||

Somebdy wake me from this bad dream!

Yes I have tried promptsql. It is slow and does not format keywords, but is the only intellisense addon that works with SSMS. A much better product is SqlAssist but only works in Visual Studio. VS on the other hand is horrible for working with dbs, so I started cutting and pasting queries into SSMS.

Shame on Microsoft for all this marketting hoopla and they basically put out archaic software that is stuck in the 70s.

|||FWIW the latest release of PromptSQL will auto-uppercase keywords, and has new caching features which should make it faster.

Wednesday, March 28, 2012

How to format a SELECT resultset as a comma separated list?

Hi,
I have the following need.
DECLARE @.Sql varchar(3000)
SET @.Sql = 'SELECT ' +
(SELECT name FROM pbajunio.sys.all_columns
WHERE object_id = object_id(@.TableName,'U')
AND system_type_id in (35,99,167,175,231,239))
+ ' FROM ' + @.TableName
--
I would like the inner SELECT (which produces a one column resultset) to be
formatted as a list separated by commas whose elements are the values of the
column of each row in the resultset.
Is this possible?
Thanks in advance,
Juan Dent, M.Sc.Hello, Juan
See: http://www.aspfaq.com/show.asp?id=2529
Razvan|||Awesome article! I hadn't seen the FOR XML trick. That is very neat.
----
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)
"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1138211041.333378.270990@.g43g2000cwa.googlegroups.com...
> Hello, Juan
> See: http://www.aspfaq.com/show.asp?id=2529
> Razvan
>|||"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:eibExsdIGHA.3984@.TK2MSFTNGP14.phx.gbl...
> Awesome article! I hadn't seen the FOR XML trick. That is very neat.
Yes,interesting.It will also be interesting to see what 'those in the know'
who have ranted that such things should be in done in the client have
to say about this:)Some will find a delicious irony in that we are
talking xml in a relational database engine let alone this particular
(unentended consequence I would bet:) solution:)
www.rac4sql.net|||Ironic, No.
Interesting, Yes
That anyone would depend on "Unintended Consequences" and other
un-documented side effects in code that can easily break after the next
Service Pack, is, very interesting :-)
"05ponyGT" <nospam@.nospam> wrote in message
news:ehV76BgIGHA.3492@.TK2MSFTNGP09.phx.gbl...
> "Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
> news:eibExsdIGHA.3984@.TK2MSFTNGP14.phx.gbl...
> Yes,interesting.It will also be interesting to see what 'those in the
> know'
> who have ranted that such things should be in done in the client have
> to say about this:)Some will find a delicious irony in that we are
> talking xml in a relational database engine let alone this particular
> (unentended consequence I would bet:) solution:)
> www.rac4sql.net
>|||Hmm...perhaps you should clarify just who is the intended
target of your arrow...?
Or is my paranoia showing...:)
"Dave Frommer" <anti@.spam.com> wrote in message
news:Oy88GPhIGHA.1836@.TK2MSFTNGP11.phx.gbl...
> Ironic, No.
> Interesting, Yes
> That anyone would depend on "Unintended Consequences" and other
> un-documented side effects in code that can easily break after the next
> Service Pack, is, very interesting :-)
>
> "05ponyGT" <nospam@.nospam> wrote in message
> news:ehV76BgIGHA.3492@.TK2MSFTNGP09.phx.gbl...
>|||The intended target is:
"anyone who would depend on "Unintended Consequences" and other
un-documented side effects in code that can easily break after the next
Service Pack"
<grin>
"05ponyGT" <nospam@.nospam> wrote in message
news:O%23pK8XhIGHA.1728@.TK2MSFTNGP09.phx.gbl...
> Hmm...perhaps you should clarify just who is the intended
> target of your arrow...?
> Or is my paranoia showing...:)
> "Dave Frommer" <anti@.spam.com> wrote in message
> news:Oy88GPhIGHA.1836@.TK2MSFTNGP11.phx.gbl...
>|||Please read at least one book -- ANY BOOK -- on RDBMS before you code.
Go to one of the first chapters and learn what FIRST nORMAL FORM (1NF)
and why it is the very foundations of SQL.
Yes, there are stinking dirty kludges to violate 1NF and the entire
concept of tiered architecture. hey, if you really want to mess up
everything and slow down your code, add XML to the mix!|||Trying to kill 2 birds with one stone....cute.
:)
"Dave Frommer" <anti@.spam.com> wrote in message
news:O7msVohIGHA.2900@.TK2MSFTNGP14.phx.gbl...
> The intended target is:
> "anyone who would depend on "Unintended Consequences" and other
> un-documented side effects in code that can easily break after the next
> Service Pack"
> <grin>
> "05ponyGT" <nospam@.nospam> wrote in message
> news:O%23pK8XhIGHA.1728@.TK2MSFTNGP09.phx.gbl...
neat.
>|||Would you really feel it a violation of 1nf to return data this way? Not
store it (that would be a "sin") but just to view it.
I completely agree that this kind of thing shouldn't be done in the data
tier, but where would you draw the line? Are aggregates wrong? Should we
not be summing data in SQL? Or adding? Should SQL simply be used to store
data? I mean, why is it always wrong to do any kind of data manipulation
here where it is easy to do in a few lines of (mostly) relational
programming?
For starters, say we have the following set (the first two columns are
functionally dependent on one another, and there would likely be more
columns):
1, 200, "Joe, Jerry, Jimmy, JoeBob",
2, 300, "Fred, Filbert"
Is it not more efficient to do this with one line of SQL code, instead of
returning:
1, 200, "Joe"
1, 200, "Jerry"
1, 200, "Jimmy"
1, 200, "JoeBob"
2, 300, "Fred"
2, 300, "Filbert"
Or two resultsets and have to write iterative code that iterates over the
set?
The first format is a great way to return data to a report writer, because
the second set can be annoying (because even when grouping this will be 4
rows for 1, and 2 rows for 2. So if 200 happened to be a number that you
had to do math on, you would either have to do some sort of division to
change it to 1, 50 on each row, or something else.
----
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)
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1138241669.307414.84260@.z14g2000cwz.googlegroups.com...
> Please read at least one book -- ANY BOOK -- on RDBMS before you code.
> Go to one of the first chapters and learn what FIRST nORMAL FORM (1NF)
> and why it is the very foundations of SQL.
> Yes, there are stinking dirty kludges to violate 1NF and the entire
> concept of tiered architecture. hey, if you really want to mess up
> everything and slow down your code, add XML to the mix!
>

How to format a date field in select query

Is it possible to format the date field create_date (mm/dd/yyyy or mm/dd/yy)
I use the following query in stored proc. will be called in the asp.net page for population the datagrid.

select id, name, create_date from actionstable;

Please help, Thank you.You can use the SQL CONVERT() function, to convert the date to an nvarchar(), or better, format the date in the presentation layer, in the datagrid itself. In the DataFormatString of the DataGrid's column that will contain the date, use 0:d

How to force some commands to run by using certain index

Hi,
Can i force some of the update command by using the
index that i want. Normally when we update something, we
will let sql to select the index, how can i choose the
index that i want in the transact-sql statement?
Can anyone teach me and give me an example?
Thanks a lot!
regards,
florence
> Can i force some of the update command by using the
> index that i want. Normally when we update something, we
> will let sql to select the index, how can i choose the
> index that i want in the transact-sql statement?
Yes, you can use optimizer hints. But a common advice is to do everything
else before using hnts. Check how to tune queries, including optimzer hints,
at
http://www.microsoft.com/technet/pro...e14.mspx#EDAA.
Dejan Sarka, SQL Server MVP
Associate Mentor
www.SolidQualityLearning.com

How to force some commands to run by using certain index

Hi,
Can i force some of the update command by using the
index that i want. Normally when we update something, we
will let sql to select the index, how can i choose the
index that i want in the transact-sql statement?
Can anyone teach me and give me an example?
Thanks a lot!
regards,
florence> Can i force some of the update command by using the
> index that i want. Normally when we update something, we
> will let sql to select the index, how can i choose the
> index that i want in the transact-sql statement?
Yes, you can use optimizer hints. But a common advice is to do everything
else before using hnts. Check how to tune queries, including optimzer hints,
at
]
Dejan Sarka, SQL Server MVP
Associate Mentor
[url]www.SolidQualityLearning.com" target="_blank">http://www.microsoft.com/technet/pr...ityLearning.com

How to force some commands to run by using certain index

Hi,
Can i force some of the update command by using the
index that i want. Normally when we update something, we
will let sql to select the index, how can i choose the
index that i want in the transact-sql statement?
Can anyone teach me and give me an example?
Thanks a lot!
regards,
florence> Can i force some of the update command by using the
> index that i want. Normally when we update something, we
> will let sql to select the index, how can i choose the
> index that i want in the transact-sql statement?
Yes, you can use optimizer hints. But a common advice is to do everything
else before using hnts. Check how to tune queries, including optimzer hints,
at
http://www.microsoft.com/technet/prodtechnol/sql/70/books/inside14.mspx#EDAA.
--
Dejan Sarka, SQL Server MVP
Associate Mentor
www.SolidQualityLearning.com

How to force CRUDs be handled through Stored Proc.

Hi,
If I want no one to be able to use then native select, delete, update etc..
and rather force the user to use stored procedure that I have included in th
e
server. how to do that?
Give:
the database has 2- accounts...one limited privileges account for the users
to use and one for me the owner. I want to deny usage of stored procedures.
plus I want to encrypt the procedure listing so now one can see the inside
Thank youDon't give the users permissions directly on the tables, only the stored pro
cedures. As for
encryption, create the procs using WITH ENCRYPTION (however, if someone want
s to, they can Google
for decryption and find it within a minute).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote in
message
news:76285543-FE12-4D61-80F9-E07A6BFDEABD@.microsoft.com...
> Hi,
> If I want no one to be able to use then native select, delete, update etc.
.
> and rather force the user to use stored procedure that I have included in
the
> server. how to do that?
> Give:
> the database has 2- accounts...one limited privileges account for the user
s
> to use and one for me the owner. I want to deny usage of stored procedures
.
> plus I want to encrypt the procedure listing so now one can see the inside
> Thank you|||"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:edPqteKSFHA.3788@.tk2msftngp13.phx.gbl...
> Don't give the users permissions directly on the tables, only the stored
> procedures. As for encryption, create the procs using WITH ENCRYPTION
> (however, if someone wants to, they can Google for decryption and find it
> within a minute).
Yeah, WITH ENCRYPTION tends to keep "honest people honest"|||Then how do i protect my stored procedures for listing?
"Michael C#" wrote:

> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote i
n
> message news:edPqteKSFHA.3788@.tk2msftngp13.phx.gbl...
> Yeah, WITH ENCRYPTION tends to keep "honest people honest"
>
>|||You can't.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote in
message
news:2505B075-0207-48EB-BA08-87C57FE3088D@.microsoft.com...
> Then how do i protect my stored procedures for listing?
> "Michael C#" wrote:
>|||Thank you all for the help,
I want to highlight that the user account is secret as well. the users must
use an application to access the db. the application has an obfuscated user
account and password that is authorized to do cruds through stored procedure
s
(assuming I denied direct access to the table) so this user account is the
only way a user can access the db. For a user to log to the SQl sever he mus
t
guess the account and password. which as securely saved/protected PKI model.
But assume he guessed the account (limited privileges) and password, and he
is now on the server. he will not be able to use the stored procedures
because I designed the procedures to take a parameter that is secret and
saved again within the application that user must use to access the
database... so the user can see the stored procedure signature I presume bu
t
have to guess the key. he is not the owner so he cant delete, and it was
saved WITH ENCRYPTION so it's encrypted and he can't see the listing and
hence see the" IF ELSE" where I check for the secret key value passed to the
procedure. Now the nightmare is that he decrypts the stored procedure...so
I have 3 questions
1- How can I protect him from opening the stored procedures?
2- Can I program the stored procedure to include check such if else
etc,,(obviously I'm novice to T-Sql)
3- can I use the e-mail mechanism from within a stored procedure to notify
me of suspicious attempts. such as when the key entered was bad. based on my
closed model on failed key attempt is too many and would trigger a
notification email.
Thank you so very much
"Tibor Karaszi" wrote:

> Don't give the users permissions directly on the tables, only the stored p
rocedures. As for
> encryption, create the procs using WITH ENCRYPTION (however, if someone wa
nts to, they can Google
> for decryption and find it within a minute).
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote i
n message
> news:76285543-FE12-4D61-80F9-E07A6BFDEABD@.microsoft.com...
>
>|||1. You can't.
2. Yes. There are procedural constructs in TSQL. See for instance IF..ELSE i
n Books Online.
3. You could use xp_sendmail or xp_smtp_sendmail (better, doesn't use MAPI,
but you need to download
and install from www.sqldev.net). Or put enough info in a table and have an
outside process (like
SQL Server Agent job) regularly read this table and send emails. Or use Noti
fication Services (free
download from MS).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote in
message
news:CC563474-6A2B-4792-86DC-5AE5CFC0F352@.microsoft.com...
> Thank you all for the help,
> I want to highlight that the user account is secret as well. the users mus
t
> use an application to access the db. the application has an obfuscated use
r
> account and password that is authorized to do cruds through stored procedu
res
> (assuming I denied direct access to the table) so this user account is the
> only way a user can access the db. For a user to log to the SQl sever he m
ust
> guess the account and password. which as securely saved/protected PKI mode
l.
> But assume he guessed the account (limited privileges) and password, and h
e
> is now on the server. he will not be able to use the stored procedures
> because I designed the procedures to take a parameter that is secret and
> saved again within the application that user must use to access the
> database... so the user can see the stored procedure signature I presume
but
> have to guess the key. he is not the owner so he cant delete, and it was
> saved WITH ENCRYPTION so it's encrypted and he can't see the listing and
> hence see the" IF ELSE" where I check for the secret key value passed to t
he
> procedure. Now the nightmare is that he decrypts the stored procedure...so
> I have 3 questions
> 1- How can I protect him from opening the stored procedures?
> 2- Can I program the stored procedure to include check such if else
> etc,,(obviously I'm novice to T-Sql)
> 3- can I use the e-mail mechanism from within a stored procedure to notify
> me of suspicious attempts. such as when the key entered was bad. based on
my
> closed model on failed key attempt is too many and would trigger a
> notification email.
> Thank you so very much
> "Tibor Karaszi" wrote:
>|||If i cant prevemt decrymption, then my only lien of defence the is embeded
acount and password. and hope the user will never abe able to guess.
Do you have better suggestions?
"Tibor Karaszi" wrote:

> 1. You can't.
> 2. Yes. There are procedural constructs in TSQL. See for instance IF..ELSE
in Books Online.
> 3. You could use xp_sendmail or xp_smtp_sendmail (better, doesn't use MAPI
, but you need to download
> and install from www.sqldev.net). Or put enough info in a table and have a
n outside process (like
> SQL Server Agent job) regularly read this table and send emails. Or use No
tification Services (free
> download from MS).
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote i
n message
> news:CC563474-6A2B-4792-86DC-5AE5CFC0F352@.microsoft.com...
>
>|||> 1- How can I protect him from opening the stored procedures?
You can't easily. The better way to get the level of security you are reques
ting
here would be to encrypt the actual data and have the stored procs merely
provide CRUD services. Thus, even if the user sees the stored proc, without
the
ability to decrypt the data itself, the stored proc by itself would useless.

> 2- Can I program the stored procedure to include check such if else
> etc,,(obviously I'm novice to T-Sql)
Not sure what you mean here.

> 3- can I use the e-mail mechanism from within a stored procedure to notify
> me of suspicious attempts. such as when the key entered was bad. based on
my
> closed model on failed key attempt is too many and would trigger a
> notification email.
> Thank you so very much
Yes but it might be trickier than you think. This can be done in the stored
procs themselves and/or in your middle layer code.
Thomas|||"Lottoman2000 NEWBE" <Lottoman2000NEWBE@.discussions.microsoft.com> wrote in
message news:7EB4CFB4-BCC6-4B7D-9204-B17B16C916E6@.microsoft.com...
> If i cant prevemt decrymption, then my only lien of defence the is embeded
> acount and password. and hope the user will never abe able to guess.
> Do you have better suggestions?
WITH ENCRYPTION keeps "honest people honest", and prevents novices from
hacking into your code, and it's not all that secure. There are just too
many tools available to decrypt SP's. Another idea might be to store your
queries internally to your application in an encrypted format and decrypt
right before execution, instead of using SP's. You'll take a performance
hit on this, however, which may or may not be negligible. This brings you
back full-circle to your original question, however, about forcing access to
tables only via SP's...sql

Monday, March 26, 2012

How to fix this error? (There is already an open DataReader associated with this Command w

This is my code:

1If Session("ctr") = False Then23 Connect()45 SQL = "SELECT * FROM counter"6 SQL = SQL & " WHERE ipaddress='" & Request.ServerVariables("REMOTE_ADDR") & "'"7 dbRead()89 If dbReader.HasRows = True Then1011 dbReader.Read()12 hits = dbReader("hits")13 hits = hits + 114 dbClose()1516 SQL = "UPDATE counter SET hits=" & hits17 SQL = SQL & " WHERE ipaddress='" & Request.ServerVariables("REMOTE_ADDR") & "'"18 dbExecute()1920 Else2122 SQL = "INSERT INTO counter(ipaddress,hits)"23 SQL = SQL & " VALUES('" & Request.ServerVariables("REMOTE_ADDR") & "',1)"24 dbExecute()2526 End If2728 Session("ctr") = True2930 End If
 
1Public Sub Connect()2 Conn = New SqlConnection("Initial Catalog=NURSETEST;User Id=sa;Password=sa;Data Source=KSNCRUZ")3 If Conn.State = ConnectionState.Open Then4 Conn.Close()5 End If6 Conn.Open()7 End Sub89 Public Sub Close()10 Conn.Close()11 Conn = Nothing12 End Sub1314 Public Sub dbExecute()15 dbCommand = New SqlCommand(SQL, Conn)16 dbCommand.ExecuteNonQuery()17 End Sub1819 Public Sub dbRead()20 dbCommand = New SqlCommand(SQL, Conn)21 dbReader = dbCommand.ExecuteReader22 End Sub2324 Public Sub dbClose()25 SQL = ""26 dbReader.Close()27 End Sub
 

You should always call the Close method when you have finished using theDataReader object. and also set dbReader Object = nothing and re intialized the object on next use

|||

1 If Session("ctr") = False Then
2
3 Connect()
4
16 SQL = "UPDATE counter SET hits=hits+1"
17 SQL = SQL & " WHERE ipaddress='" & Request.ServerVariables("REMOTE_ADDR") & "'"

SQL = SQL & " IF @.@.Rowcount=0"
22 SQL =SQL & " INSERT INTO counter(ipaddress,hits)"
23 SQL = SQL & " VALUES('" & Request.ServerVariables("REMOTE_ADDR") & "',1)"
24 dbExecute()
25 Close()

27
28 Session("ctr") = True
29
30 End If

sql

Wednesday, March 21, 2012

How to find the MDF file size.

Hi,
I want to find the size of the MDF file for a select database.
How can I do this?
Thanks in advance.
Nadee.Try this:
SELECT size*8192 as FileSize
FROM master..sysaltfiles
WHERE fileid=1 AND dbid=DB_ID('YourDatabase')
Razvan|||Gon
Also ,take a look at sp_helpdb 'database' system stored procedure
If you have more than one file
SELECT RTRIM(filename) ,SIZE
FROM sysfiles
WHERE fileid = (SELECT MIN(fileid) FROM sysfiles)
UNION ALL
SELECT RTRIM(filename) ,SIZE
FROM sysfiles
WHERE fileid > (SELECT MIN(fileid) FROM sysfiles) AND
fileid < (SELECT MAX(fileid) FROM sysfiles)
UNION ALL
SELECT RTRIM(filename),SIZE
FROM sysfiles
WHERE fileid = (SELECT MAX(fileid) FROM sysfiles)
"Gon Nadiya" <WazHot@.mymail.com> wrote in message
news:u$f5%23mllFHA.420@.TK2MSFTNGP09.phx.gbl...
> Hi,
> I want to find the size of the MDF file for a select database.
> How can I do this?
> Thanks in advance.
> Nadee.
>|||Used the extended stored procedure xp_getfiledetails to give you size of fil
e
but the name of the file will be on NT format example 'BL4BB2~1.BKP'
EXEC master.dbo.xp_getfiledetails
'\\Blptcsqlmon01\backup\BLDALSTGSQL04\TR
AN_Backup\blcms_TRAN_BU_20050801_00.
bkp'
"Gon Nadiya" wrote:

> Hi,
> I want to find the size of the MDF file for a select database.
> How can I do this?
> Thanks in advance.
> Nadee.
>
>|||Hi URI,
Thanks for the support.
It worked with no issues.
Nadee.
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:OL0qrQmlFHA.1048@.tk2msftngp13.phx.gbl...
> Gon
> Also ,take a look at sp_helpdb 'database' system stored procedure
> If you have more than one file
>
> SELECT RTRIM(filename) ,SIZE
> FROM sysfiles
> WHERE fileid = (SELECT MIN(fileid) FROM sysfiles)
> UNION ALL
> SELECT RTRIM(filename) ,SIZE
> FROM sysfiles
> WHERE fileid > (SELECT MIN(fileid) FROM sysfiles) AND
> fileid < (SELECT MAX(fileid) FROM sysfiles)
> UNION ALL
> SELECT RTRIM(filename),SIZE
> FROM sysfiles
> WHERE fileid = (SELECT MAX(fileid) FROM sysfiles)
> "Gon Nadiya" <WazHot@.mymail.com> wrote in message
> news:u$f5%23mllFHA.420@.TK2MSFTNGP09.phx.gbl...
>|||Does anyone know how to get file size in Dos - need way to verify file size
is not equal to 0 bytes.
JC
"JosephPruiett" wrote:
> Used the extended stored procedure xp_getfiledetails to give you size of f
ile
> but the name of the file will be on NT format example 'BL4BB2~1.BKP'
> EXEC master.dbo.xp_getfiledetails
> '\\Blptcsqlmon01\backup\BLDALSTGSQL04\TR
AN_Backup\blcms_TRAN_BU_20050801_0
0.bkp'
>
>
> "Gon Nadiya" wrote:
>|||Not sure I understand you, bit how about DIR?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"JC" <JC@.discussions.microsoft.com> wrote in message
news:44944802-D81D-481A-A475-0D82E0EC04BA@.microsoft.com...
> Does anyone know how to get file size in Dos - need way to verify file si
ze
> is not equal to 0 bytes.
> JC
> "JosephPruiett" wrote:
>|||sp_helpfile
"JC" <JC@.discussions.microsoft.com> wrote in message
news:44944802-D81D-481A-A475-0D82E0EC04BA@.microsoft.com...
> Does anyone know how to get file size in Dos - need way to verify file
> size
> is not equal to 0 bytes.
> JC
> "JosephPruiett" wrote:
>sql

How to find the in Progress job in MSDB database

Hello,
I am try to find which job is in progress.
Then I start a job A. run a statement like:
select * from sysjobhistory where job_id = 'A' and
run_status = 4
it return nothing, even I know the job it is running.
Can anybody tell me how to get information about those job
in progress from MSDB database?
Thanks in advance...Don't feel bad about not finding it. It isn't in the database. It is
actually in the shared memory between SQL Agent and SQL Server. I don't
know of any way to access it either.
--
Geoff N. Hiten
Microsoft SQL Server MVP
Senior Database Administrator
Careerbuilder.com
"Harry G" <anonymous@.discussions.microsoft.com> wrote in message
news:04ad01c3d6f7$aa1624f0$a101280a@.phx.gbl...
> Hello,
> I am try to find which job is in progress.
> Then I start a job A. run a statement like:
> select * from sysjobhistory where job_id = 'A' and
> run_status = 4
> it return nothing, even I know the job it is running.
> Can anybody tell me how to get information about those job
> in progress from MSDB database?
> Thanks in advance...|||Hi,
Please execute the procedure
exec msdb..sp_help_job @.job_id = 0x3F2224EAAFD7A9418A4643AF5C020379,
@.job_aspect = N'job'
(replcae the jobid with your job id)
current_execution_status =1 then Job executing
current_execution_status =4 then not Running
Thanks
Hari
MCDBA
"Harry G" <anonymous@.discussions.microsoft.com> wrote in message
news:04ad01c3d6f7$aa1624f0$a101280a@.phx.gbl...
> Hello,
> I am try to find which job is in progress.
> Then I start a job A. run a statement like:
> select * from sysjobhistory where job_id = 'A' and
> run_status = 4
> it return nothing, even I know the job it is running.
> Can anybody tell me how to get information about those job
> in progress from MSDB database?
> Thanks in advance...

How to find the first not used Char with a SELECT

I have a table Names with two fields:
ChID varchar(1)
Name varchar(25)
where the ChID char is in a range a .. z
(there will never be more then 27 records)
Some chars are used, some not
Two examples:
eg.
I have 4 records: CharID b, c, e, and f are used
I want to find the first not used char
In this example it is the char a
eg.
I have 5 records: CharID a, b, c, e, and f are used
I want to find the first not used char
In this example it is the char d.
Is a SELECT statement possible for finding the first not used Char?
How would such a statement be?Hi Henk,
Assuming all your ChID's are lower case, and a-z in ASCII:
CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
INSERT INTO Names(ChID) VALUES('f')
INSERT INTO Names(ChID) VALUES('b')
INSERT INTO Names(ChID) VALUES('c')
INSERT INTO Names(ChID) VALUES('e')
SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) =ASCII(Names.ChID)-1 )
AND ChID > 'a'
DROP TABLE Names
How do you get _27_ rows btw?
--
Jacco Schalkwijk MCDBA, MCSD, MCSE
Database Administrator
Eurostop Ltd.
"Henk Schreij" <henk@.schreijDOTnl> wrote in message
news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> I have a table Names with two fields:
> ChID varchar(1)
> Name varchar(25)
> where the ChID char is in a range a .. z
> (there will never be more then 27 records)
> Some chars are used, some not
> Two examples:
> eg.
> I have 4 records: CharID b, c, e, and f are used
> I want to find the first not used char
> In this example it is the char a
> eg.
> I have 5 records: CharID a, b, c, e, and f are used
> I want to find the first not used char
> In this example it is the char d.
> Is a SELECT statement possible for finding the first not used Char?
> How would such a statement be?
>|||Jacco thanks,
It is a wonderful simple solution, exactly what I wanted.
You asked: How do you get _27_ rows btw?
Do you mean: How do you control that there will not be more then 27 rows?
The solution is that I use this SQL statement in a Delphi application. There
I use RecordCount, to limit the amount of records.
"Jacco Schalkwijk" <NOSPAMjaccos@.eurostop.co.uk> schreef in bericht
news:ur2NovtdDHA.1448@.TK2MSFTNGP12.phx.gbl...
> Hi Henk,
>
> Assuming all your ChID's are lower case, and a-z in ASCII:
> CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> INSERT INTO Names(ChID) VALUES('f')
> INSERT INTO Names(ChID) VALUES('b')
> INSERT INTO Names(ChID) VALUES('c')
> INSERT INTO Names(ChID) VALUES('e')
> SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
> WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) => ASCII(Names.ChID)-1 )
> AND ChID > 'a'
> DROP TABLE Names
> How do you get _27_ rows btw?
> --
> Jacco Schalkwijk MCDBA, MCSD, MCSE
> Database Administrator
> Eurostop Ltd.
>
> "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > I have a table Names with two fields:
> > ChID varchar(1)
> > Name varchar(25)
> > where the ChID char is in a range a .. z
> > (there will never be more then 27 records)
> > Some chars are used, some not
> >
> > Two examples:
> > eg.
> > I have 4 records: CharID b, c, e, and f are used
> > I want to find the first not used char
> > In this example it is the char a
> > eg.
> > I have 5 records: CharID a, b, c, e, and f are used
> > I want to find the first not used char
> > In this example it is the char d.
> >
> > Is a SELECT statement possible for finding the first not used Char?
> > How would such a statement be?
> >
> >
>|||the previous code won't work in case 'abc' (must be 'd') and in case of
empty table (must be 'a'). this one looks not so fine, but works
declare @.id varchar(1), @.fo varchar(1)
set @.fo='a'
declare MV cursor for select distinct lower(ChID) from Names where ChID
between 'a' and 'z' order by 1
Open MV
FETCH NEXT FROM MV INTO @.id
WHILE @.@.FETCH_STATUS = 0
BEGIN
if @.fo<>@.id BREAK
set @.fo=(CHAR(ASCII(@.fo) + 1))
FETCH NEXT FROM MV INTO @.id
END
CLOSE MV
DEALLOCATE MV
IF ASCII(@.fo)>122 set @.fo=NULL
print ISNULL(@.fo,'-')|||Hi Henk,
I meant that usually there are only 26 letters from a-z (well, definitly in
ASCII), so I was wondering where you got the 27th from?
--
Jacco Schalkwijk MCDBA, MCSD, MCSE
Database Administrator
Eurostop Ltd.
"Henk Schreij" <henk@.schreijDOTnl> wrote in message
news:%238Xc8$wdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> Jacco thanks,
> It is a wonderful simple solution, exactly what I wanted.
> You asked: How do you get _27_ rows btw?
> Do you mean: How do you control that there will not be more then 27 rows?
> The solution is that I use this SQL statement in a Delphi application.
There
> I use RecordCount, to limit the amount of records.
> "Jacco Schalkwijk" <NOSPAMjaccos@.eurostop.co.uk> schreef in bericht
> news:ur2NovtdDHA.1448@.TK2MSFTNGP12.phx.gbl...
> > Hi Henk,
> >
> >
> > Assuming all your ChID's are lower case, and a-z in ASCII:
> >
> > CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> >
> > INSERT INTO Names(ChID) VALUES('f')
> > INSERT INTO Names(ChID) VALUES('b')
> > INSERT INTO Names(ChID) VALUES('c')
> > INSERT INTO Names(ChID) VALUES('e')
> >
> > SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
> > WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) => > ASCII(Names.ChID)-1 )
> > AND ChID > 'a'
> >
> > DROP TABLE Names
> >
> > How do you get _27_ rows btw?
> >
> > --
> > Jacco Schalkwijk MCDBA, MCSD, MCSE
> > Database Administrator
> > Eurostop Ltd.
> >
> >
> > "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> > news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > > I have a table Names with two fields:
> > > ChID varchar(1)
> > > Name varchar(25)
> > > where the ChID char is in a range a .. z
> > > (there will never be more then 27 records)
> > > Some chars are used, some not
> > >
> > > Two examples:
> > > eg.
> > > I have 4 records: CharID b, c, e, and f are used
> > > I want to find the first not used char
> > > In this example it is the char a
> > > eg.
> > > I have 5 records: CharID a, b, c, e, and f are used
> > > I want to find the first not used char
> > > In this example it is the char d.
> > >
> > > Is a SELECT statement possible for finding the first not used Char?
> > > How would such a statement be?
> > >
> > >
> >
> >
>|||Sorry for the crosspost,
I also found out that the answer is not always correct.
(also thanks to news.rinet from russia)
I study this code to see if its better then the code I posted.
"Jacco Schalkwijk" <NOSPAMjaccos@.eurostop.co.uk> schreef in bericht
news:uyhXeT3dDHA.2816@.TK2MSFTNGP10.phx.gbl...
> Hi Henk,
> As pointed out in the other post it didn't work in all situations, but I
> have made the corrections in the code below.
> What the code now does is first check if there is a row that is 'a' (WHEN
> NOT EXISTS(SELECT NULL FROM Names n2 WHERE ChID = 'a') THEN 'a') , and if
> there isn't than that is of course the value you're looking for. This also
> catches the empty table. Next it will find the lowest ChID for which the
> next highest ChID in alphabetical order doesn't exists.
> You can also use a table variable with a-z in it and compare against that
> (second script)
> CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> INSERT INTO Names(ChID) VALUES('a')
> INSERT INTO Names(ChID) VALUES('b')
> INSERT INTO Names(ChID) VALUES('c')
> INSERT INTO Names(ChID) VALUES('d')
> SELECT CASE WHEN NOT EXISTS(SELECT NULL FROM Names n2 WHERE ChID = 'a')
THEN
> 'a' ELSE
> MIN(CHAR(ASCII(ChID) + 1))
> END
> FROM Names
> WHERE
> NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) => ASCII(Names.ChID)+1 )
> DROP TABLE Names
>
> CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> INSERT INTO Names(ChID) VALUES('a')
> INSERT INTO Names(ChID) VALUES('b')
> INSERT INTO Names(ChID) VALUES('f')
> INSERT INTO Names(ChID) VALUES('d')
> DECLARE @.letters TABLE(letter char(1))
> DECLARE @.i TINYINT
> SET @.i = 97
> WHILE @.i < 123
> BEGIN
> INSERT INTO @.letters(letter) VALUES(CHAR(@.i))
> SET @.i = @.i +1
> END
> SELECT MIN(letter)
> FROM @.letters l
> LEFT OUTER JOIN Names n
> ON l.letter = n.ChID
> WHERE n.ChID IS NULL
>
> DROP TABLE Names
>
> --
> Jacco Schalkwijk MCDBA, MCSD, MCSE
> Database Administrator
> Eurostop Ltd.
>
> "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> news:eIkC4dxdDHA.2168@.TK2MSFTNGP09.phx.gbl...
> > Jacco after studying your code, I must say it is not so simple as I
first
> > thought.
> > I do not understand the working of this piece of art yet, but I'am
trying.
> >
> > Oh, btw, a..z is 26 chars, not 27. I have to go to the primary school
> again
> > <g>.
> >
> > "Jacco Schalkwijk" <NOSPAMjaccos@.eurostop.co.uk> schreef in bericht
> > news:ur2NovtdDHA.1448@.TK2MSFTNGP12.phx.gbl...
> >
> > > SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
> > > WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) => > > ASCII(Names.ChID)-1 )
> > > AND ChID > 'a'
> > >
> > > How do you get _27_ rows btw?
> > >
> > > "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> > > news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > > > I have a table Names with two fields:
> > > > ChID varchar(1)
> > > > Name varchar(25)
> > > > where the ChID char is in a range a .. z
> > > > (there will never be more then 27 records)
> > > > Some chars are used, some not
> > > >
> > > > Two examples:
> > > > eg.
> > > > I have 4 records: CharID b, c, e, and f are used
> > > > I want to find the first not used char
> > > > In this example it is the char a
> > > > eg.
> > > > I have 5 records: CharID a, b, c, e, and f are used
> > > > I want to find the first not used char
> > > > In this example it is the char d.
> > > >
> > > > Is a SELECT statement possible for finding the first not used Char?
> > > > How would such a statement be?
> >
> >
> >
>|||I'am sorry that I have to tell you that the sql statement did'nt give the
correct answer.
Example:
CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
INSERT INTO Names(ChID) VALUES('f')
INSERT INTO Names(ChID) VALUES('a')
INSERT INTO Names(ChID) VALUES('b')
INSERT INTO Names(ChID) VALUES('c')
SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
WHERE NOT EXISTS(SELECT NULL FROM Names n2
WHERE ASCII(n2.ChID) = ASCII(Names.ChID)-1 )
AND ChID > 'a'
DROP TABLE Names
The result is an 'e' in stead of 'd' (the first free char)
But you showed me a way to handle this problem (thanks for that).
I made this statement:
CREATE TABLE Names (ChID varchar(1), Name varchar(25) NULL)
INSERT INTO Names(ChID) VALUES('c')
INSERT INTO Names(ChID) VALUES('b')
INSERT INTO Names(ChID) VALUES('a')
INSERT INTO Names(ChID) VALUES('z')
SELECT ISNULL(MIN(Nw), 'a') FROM (
SELECT CHAR(MIN(ASCII(ChID) + 1)) AS Nw
FROM Names WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM Names)
UNION
SELECT (CASE WHEN (MIN(ChID) >= 'b') THEN 'a' END) AS Nw FROM Names) Tmp
DROP TABLE Names
It gives the correct answers (the ISNULL is for a empty table)
but the code is not very well designed, using a UNION.
Is it possible to get the same result without a union?
Henk.
> > > "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> > > news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > > > I have a table Names with two fields:
> > > > ChID varchar(1)
> > > > Name varchar(25)
> > > > where the ChID char is in a range a .. z
> > > > (there will never be more then 27 records)
> > > > Some chars are used, some not
> > > >
> > > > Two examples:
> > > > eg.
> > > > I have 4 records: CharID b, c, e, and f are used
> > > > I want to find the first not used char
> > > > In this example it is the char a
> > > > eg.
> > > > I have 5 records: CharID a, b, c, e, and f are used
> > > > I want to find the first not used char
> > > > In this example it is the char d.
> > > >
> > > > Is a SELECT statement possible for finding the first not used Char?
> > > > How would such a statement be?|||Hi Henk,
The WHERE clause you have posted here
WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM Names)
is logically equivalent to the WHERE clause in my post in the other part of
this thread
WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) =ASCII(Names.ChID)+1)
I know that using IN is easier to understand than using EXISTS, but I advise
you to try to understand the use of EXISTS, because IN is limited to an
equality on one column, where with EXISTS you can use multiple columns and
different operators (<, >, BETWEEN, etc). On top of that EXISTS will always
perform as least as well as IN, and often it performs a lot better.
--
Jacco Schalkwijk MCDBA, MCSD, MCSE
Database Administrator
Eurostop Ltd.
"Henk Schreij" <henk@.schreijDOTnl> wrote in message
news:uDQfLY5dDHA.3584@.tk2msftngp13.phx.gbl...
> I made a syntesis of your and my statements:
> CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> INSERT INTO Names(ChID) VALUES('d')
> INSERT INTO Names(ChID) VALUES('b')
> INSERT INTO Names(ChID) VALUES('c')
> INSERT INTO Names(ChID) VALUES('z')
> SELECT CASE
> WHEN NOT EXISTS (SELECT NULL FROM Names WHERE ChID = 'a') THEN 'a'
> ELSE CHAR(MIN(ASCII(ChID) + 1)) END
> FROM Names WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM Names)
> I think this is the most elegant solution.
> Thanks a lot.
> Henk
> "Henk Schreij" <henk@.schreijDOTnl> schreef in bericht
> news:OPJslo4dDHA.3992@.TK2MSFTNGP11.phx.gbl...
> > I'am sorry that I have to tell you that the sql statement did'nt give
the
> > correct answer.
> >
> > Example:
> > CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> > INSERT INTO Names(ChID) VALUES('f')
> > INSERT INTO Names(ChID) VALUES('a')
> > INSERT INTO Names(ChID) VALUES('b')
> > INSERT INTO Names(ChID) VALUES('c')
> >
> > SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
> > WHERE NOT EXISTS(SELECT NULL FROM Names n2
> > WHERE ASCII(n2.ChID) = ASCII(Names.ChID)-1 )
> > AND ChID > 'a'
> >
> > DROP TABLE Names
> >
> > The result is an 'e' in stead of 'd' (the first free char)
> >
> > But you showed me a way to handle this problem (thanks for that).
> >
> > I made this statement:
> > CREATE TABLE Names (ChID varchar(1), Name varchar(25) NULL)
> > INSERT INTO Names(ChID) VALUES('c')
> > INSERT INTO Names(ChID) VALUES('b')
> > INSERT INTO Names(ChID) VALUES('a')
> > INSERT INTO Names(ChID) VALUES('z')
> >
> > SELECT ISNULL(MIN(Nw), 'a') FROM (
> > SELECT CHAR(MIN(ASCII(ChID) + 1)) AS Nw
> > FROM Names WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM
> Names)
> > UNION
> > SELECT (CASE WHEN (MIN(ChID) >= 'b') THEN 'a' END) AS Nw FROM Names)
Tmp
> >
> > DROP TABLE Names
> >
> > It gives the correct answers (the ISNULL is for a empty table)
> > but the code is not very well designed, using a UNION.
> >
> > Is it possible to get the same result without a union?
> >
> > Henk.
> > > > > "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> > > > > news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > > > > > I have a table Names with two fields:
> > > > > > ChID varchar(1)
> > > > > > Name varchar(25)
> > > > > > where the ChID char is in a range a .. z
> > > > > > (there will never be more then 27 records)
> > > > > > Some chars are used, some not
> > > > > >
> > > > > > Two examples:
> > > > > > eg.
> > > > > > I have 4 records: CharID b, c, e, and f are used
> > > > > > I want to find the first not used char
> > > > > > In this example it is the char a
> > > > > > eg.
> > > > > > I have 5 records: CharID a, b, c, e, and f are used
> > > > > > I want to find the first not used char
> > > > > > In this example it is the char d.
> > > > > >
> > > > > > Is a SELECT statement possible for finding the first not used
> Char?
> > > > > > How would such a statement be?
>
>|||Jacco, thank you for this extra explanation.
I'll study the Exists in my SQL-book and try to use it more often, as it has
indeed some benefits over the IN statement.
"Jacco Schalkwijk" <NOSPAMjaccos@.eurostop.co.uk> schreef in bericht
news:#8QRez5dDHA.1460@.TK2MSFTNGP10.phx.gbl...
> Hi Henk,
> The WHERE clause you have posted here
> WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM Names)
> is logically equivalent to the WHERE clause in my post in the other part
of
> this thread
> WHERE NOT EXISTS(SELECT NULL FROM Names n2 WHERE ASCII(n2.ChID) => ASCII(Names.ChID)+1)
> I know that using IN is easier to understand than using EXISTS, but I
advise
> you to try to understand the use of EXISTS, because IN is limited to an
> equality on one column, where with EXISTS you can use multiple columns and
> different operators (<, >, BETWEEN, etc). On top of that EXISTS will
always
> perform as least as well as IN, and often it performs a lot better.
> --
> Jacco Schalkwijk MCDBA, MCSD, MCSE
> Database Administrator
> Eurostop Ltd.
>
> "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> news:uDQfLY5dDHA.3584@.tk2msftngp13.phx.gbl...
> > I made a syntesis of your and my statements:
> > CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> > INSERT INTO Names(ChID) VALUES('d')
> > INSERT INTO Names(ChID) VALUES('b')
> > INSERT INTO Names(ChID) VALUES('c')
> > INSERT INTO Names(ChID) VALUES('z')
> >
> > SELECT CASE
> > WHEN NOT EXISTS (SELECT NULL FROM Names WHERE ChID = 'a') THEN 'a'
> > ELSE CHAR(MIN(ASCII(ChID) + 1)) END
> > FROM Names WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM
Names)
> >
> > I think this is the most elegant solution.
> > Thanks a lot.
> > Henk
> >
> > "Henk Schreij" <henk@.schreijDOTnl> schreef in bericht
> > news:OPJslo4dDHA.3992@.TK2MSFTNGP11.phx.gbl...
> > > I'am sorry that I have to tell you that the sql statement did'nt give
> the
> > > correct answer.
> > >
> > > Example:
> > > CREATE TABLE NAMES(ChID varchar(1), Name varchar(25) NULL)
> > > INSERT INTO Names(ChID) VALUES('f')
> > > INSERT INTO Names(ChID) VALUES('a')
> > > INSERT INTO Names(ChID) VALUES('b')
> > > INSERT INTO Names(ChID) VALUES('c')
> > >
> > > SELECT MIN(CHAR(ASCII(ChID) - 1)) FROM Names
> > > WHERE NOT EXISTS(SELECT NULL FROM Names n2
> > > WHERE ASCII(n2.ChID) = ASCII(Names.ChID)-1 )
> > > AND ChID > 'a'
> > >
> > > DROP TABLE Names
> > >
> > > The result is an 'e' in stead of 'd' (the first free char)
> > >
> > > But you showed me a way to handle this problem (thanks for that).
> > >
> > > I made this statement:
> > > CREATE TABLE Names (ChID varchar(1), Name varchar(25) NULL)
> > > INSERT INTO Names(ChID) VALUES('c')
> > > INSERT INTO Names(ChID) VALUES('b')
> > > INSERT INTO Names(ChID) VALUES('a')
> > > INSERT INTO Names(ChID) VALUES('z')
> > >
> > > SELECT ISNULL(MIN(Nw), 'a') FROM (
> > > SELECT CHAR(MIN(ASCII(ChID) + 1)) AS Nw
> > > FROM Names WHERE NOT (ASCII(ChID) + 1) IN (SELECT ASCII(ChID) FROM
> > Names)
> > > UNION
> > > SELECT (CASE WHEN (MIN(ChID) >= 'b') THEN 'a' END) AS Nw FROM Names)
> Tmp
> > >
> > > DROP TABLE Names
> > >
> > > It gives the correct answers (the ISNULL is for a empty table)
> > > but the code is not very well designed, using a UNION.
> > >
> > > Is it possible to get the same result without a union?
> > >
> > > Henk.
> > > > > > "Henk Schreij" <henk@.schreijDOTnl> wrote in message
> > > > > > news:O$CUghtdDHA.1944@.TK2MSFTNGP12.phx.gbl...
> > > > > > > I have a table Names with two fields:
> > > > > > > ChID varchar(1)
> > > > > > > Name varchar(25)
> > > > > > > where the ChID char is in a range a .. z
> > > > > > > (there will never be more then 27 records)
> > > > > > > Some chars are used, some not
> > > > > > >
> > > > > > > Two examples:
> > > > > > > eg.
> > > > > > > I have 4 records: CharID b, c, e, and f are used
> > > > > > > I want to find the first not used char
> > > > > > > In this example it is the char a
> > > > > > > eg.
> > > > > > > I have 5 records: CharID a, b, c, e, and f are used
> > > > > > > I want to find the first not used char
> > > > > > > In this example it is the char d.
> > > > > > >
> > > > > > > Is a SELECT statement possible for finding the first not used
> > Char?
> > > > > > > How would such a statement be?
> >
> >
> >
>

Monday, March 19, 2012

how to find size of the index

sp_spaceused <tablename>
select dpages,reserved,used from sysindexes where id=357576312
These values seem to be different. Can somebody explan?sp_spaceused <tablename>
name rows reserved data index_size unused
<tablename> 1998 136 KB 72 KB 8 KB 56 KB
select id from sysobjects where name = <table_name>
357576312
select dpages,reserved,used from sysindexes where id=357576312
dpages reserved used
9 17 10
select (9*8)+(17*8)+(10*8) 288
select (136+72+8+56) 272
"mani" wrote:
> sp_spaceused <tablename>
> select dpages,reserved,used from sysindexes where id=357576312
>
> These values seem to be different. Can somebody explan?|||You need a little math help:
Reserved = Data + Index + Unused = Used + Unused
17 Reserved Pages * 8 KB/page = 136 KB =9 Data Pages * 8 KB/page = 72 KB +
1 Index Page * 8 KB/page = 10 Used Pages - 9 Data Pages = 8 KB
(9 Data Pages + 1 Index Page) * 8 KB/page = 10 Used Pages * 8 KB/page = 80 KB
Now, (17 Reserved Pages - 10 Used Pages) * 8 KB/page =7 Unused Pages * 8 KB/page = 56 KB.
You just have to figure out which pieces are which but it is all consistent.
Your problem was that you added Reserved to what was used: reserved is
already the grand total you were aiming for.
Hope this helps. What also can help is to read what the authors wrote: take
a look at the sp_spaceused stored procedure,
USE master
GO
EXEC dbo.sp_helptext 'dbo.sp_spaceused'
GO
You can find a lot of interesting information by examining the code for the
system procedures.
Sincerely,
Anthony Thomas
"mani" wrote:
> sp_spaceused <tablename>
> name rows reserved data index_size unused
> <tablename> 1998 136 KB 72 KB 8 KB 56 KB
>
> select id from sysobjects where name = <table_name>
> 357576312
> select dpages,reserved,used from sysindexes where id=357576312
> dpages reserved used
> 9 17 10
>
> select (9*8)+(17*8)+(10*8) 288
> select (136+72+8+56) 272
> "mani" wrote:
> > sp_spaceused <tablename>
> >
> > select dpages,reserved,used from sysindexes where id=357576312
> >
> >
> > These values seem to be different. Can somebody explan?

how to find records in database using select

I need to be able to find certain data as the user has submitted that data twice and delete one record,except that have hundreds of tables and don't know the table where she would have submitted the data, but I have some other key info that I can start with.

My question is,how do i select a record from the database if I don't know the table it comes from?

Could somebody give me an expamle please?How did they submit the data? Do you know the data submitted? You have to have something to go on.|||Can you pose the question exactly as the teacher wrote it in your assignment? Just type it verbatim into a posting, and you'll get a much better quality answer.

-PatP

Monday, March 12, 2012

how to find out the SP version?

Is there any convinient way to find out the service pack version on SQL
Server 2000?
select @.@.version revelas info about the OS SP version, but not about the SQL
Server SP version.
Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38
Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows
NT 5.2 (Build 3790: Service Pack 1)8.00.194 no sp
8.00.384 sp1
8.00.532 sp2
8.00.760 sp3
8.00.818 Sp3 with cumulative patch 03-031
8.00.2039 Sp4
"Magnus Österberg" <magnus.osterberg@.abo.fi> wrote in message
news:dg9abt$kv3$1@.plaza.suomi.net...
> Is there any convinient way to find out the service pack version on SQL
> Server 2000?
> select @.@.version revelas info about the OS SP version, but not about the
> SQL Server SP version.
> Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38
> Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows
> NT 5.2 (Build 3790: Service Pack 1)
>
>|||HOW TO: identify your SQL Server Service Pack version and edition
http://support.microsoft.com/default.aspx?scid=kb;en-us;321185
AMB
"Magnus Ã?sterberg" wrote:
> Is there any convinient way to find out the service pack version on SQL
> Server 2000?
> select @.@.version revelas info about the OS SP version, but not about the SQL
> Server SP version.
> Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38
> Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows
> NT 5.2 (Build 3790: Service Pack 1)
>
>|||Hi Magnus
A fuller list of version number can be found at
http://www.sqlsecurity.com/DesktopDefault.aspx?tabid=37 or
http://www.aspfaq.com/sql2000builds.asp
John
"Magnus Österberg" <magnus.osterberg@.abo.fi> wrote in message
news:dg9abt$kv3$1@.plaza.suomi.net...
> Is there any convinient way to find out the service pack version on SQL
> Server 2000?
> select @.@.version revelas info about the OS SP version, but not about the
> SQL Server SP version.
> Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38
> Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows
> NT 5.2 (Build 3790: Service Pack 1)
>
>

Friday, February 24, 2012

How to find binding errors to views

I have a view with no table present such as
Create table T1
(Col1 int)
go
Create view V1
as
select * from T1
go
drop table T1
go
select * from V1
I want to be able to run a query against a database that would give me all
the views that are inconsistent as above
I tried dbcc checkdb and dbcc checktable and it doesnt seem to work..I don't think there is a single way to get the list of all the views with
binding errors. Perhaps, one option is to execute sp_refreshview in a
cursor/loop which will error out.
If this is something you'd want to preserve for any future views, perhaps
you should consider using explicit column names in SELECT clauses, two part
naming in FROM clauses and WITH SCHEMABINDING option while creating the
view.
--
Anith|||I tried the cursor approach but the cursor aborts after it finds the first
violation. How can I let it continue ?
"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:eHi%23IVnjFHA.2444@.TK2MSFTNGP10.phx.gbl...
> I don't think there is a single way to get the list of all the views with
> binding errors. Perhaps, one option is to execute sp_refreshview in a
> cursor/loop which will error out.
> If this is something you'd want to preserve for any future views, perhaps
> you should consider using explicit column names in SELECT clauses, two
part
> naming in FROM clauses and WITH SCHEMABINDING option while creating the
> view.
> --
> Anith
>|||I do a build of the database using the source code using DB Ghost Database
Builder. That way all errors are quickly reported and can therefore be fixed.
The builder builds objects at around 1000/minute making this a very quick and
extremely thorough process.
regards,
Mark Baekdal
http://www.dbghost.com
http://www.innovartis.co.uk
+44 (0)208 241 1762
Build, Comparison and Synchronization from Source Control = Database change
management for SQL Server
"Hassan" wrote:
> I have a view with no table present such as
> Create table T1
> (Col1 int)
> go
> Create view V1
> as
> select * from T1
> go
> drop table T1
> go
> select * from V1
> I want to be able to run a query against a database that would give me all
> the views that are inconsistent as above
> I tried dbcc checkdb and dbcc checktable and it doesnt seem to work..
>
>

Sunday, February 19, 2012

how to find a simple quote in a row

Hi,
I have a table with a "description" row.
In this row I may have some simple quote (') character.
How can I select them ?
something like :
select * from myTable where description like %'%
thanksselect * from myTable where description like %''%

Use TWO single quotes. They are treated as one.|||don't forget the quotes around the pattern :)

... where description like '%''%'|||Other alternative is

select * from tableName where charindex('''',Colname)>0

How to find a perticular row?

Hi all,
I want to select last but one row in a table. I shouldn't use pk_id of the table ,because the entries in a table are jumbled.
I want the last but one row that as entered.
Thanks in advance
venkatHi vencat

This gets right to the nub of relational theory. Tables in an RDBMS are sets of data. Think of a Venn diagram - there is no order right? Just some "clouds" to represent sets. As such there is no such thing as last or first or last but one in a relational table. Order of insertion and physical order on disk is irrelevent. So - unless you have used some sort of timestamp for when you inserted the data (say a column with a default value of GETDATE()) or some other method of determining a logical order of the data then you cannot satisfy your requirement

HTH|||select top 1 * from yourtable order by newid()

;)|||select top 1 * from yourtable order by newid()

;)

doesn't that just grab a random row?|||Originally Posted by jezemine
select top 1 * from yourtable order by newid()
this is definitely not a correct way to select last but one row. I don't think it is not possbile if you don't have timestamp or identity or smiliar column.|||doesn't that just grab a random row?
this is definitely not a correct way to select last but one row. I don't think it is not possbile if you don't have timestamp or identity or smiliar column.Did you guys miss the wink? And Jesse's increasing ratio of sarcy to serious posts? ;)

Anyway - everyone knows it is:
select top 1 * from yourtable order by newid() DESC|||select top 1 *
from ( select t.*, newid() as random_number
from yourtable as t ) as inline_view
order by random_number desc|||SELECT TOP 1 A_SQL99_compliant_derived_table.*
FROM --A SQL99 compliant derived table
(SELECT *
, rn = row_number() OVER (ORDER BY newid() DESC)
FROM meTable) AS A_SQL99_compliant_derived_table
WHERE rn = 1
My - we are a witty bunch.

I said witty :)|||very nice, and very elegant, too

but shouldn't it be An_SQL99_compliant_derived_table|||very nice, and very elegant, tooThanks :cool: I like to write tight, elegent code to meet the requirements.

but shouldn't it be An_SQL99_compliant_derived_tableI'm an old skooler Rudy - it is pronounced SEQUEL in the flump household.:)|||ok, ok, i feel bad now. ;)

this will give you the second to last row, where "last" is determined by ordering the "item" column alphabetically.

declare @.t table (item varchar(10))

insert into @.t
select 'aaa' union all
select 'bbb' union all
select 'ccc' union all
select 'ddd' union all
select 'eee' union all
select 'fff'

select top 1 a.* from
(select top 2 * from @.t order by item desc) a
order by item asc|||select top 1 * from yourtable order by newid()

;)

-It is retrieving only row 1 based on the primary key of the table.I am not willing to use primary key.

Thanks|||Ok..Guys I tested all your posts.but no one retrieving the last but row.But some of them returning last row depending on primary key of the table ,that i can achieve easily .but i don't want to use primary key...

when i "select * " it is retrieving always a some order (but this order is same for all times) and where the rows are jumbled.i.e showing in an order they were entered.

I want that last but one row showing in "select * from mytable" result set..

Thanks for great help..!!|||ok, ok, i feel bad now. ;)

this will give you the second to last row, where "last" is determined by ordering the "item" column alphabetically.

declare @.t table (item varchar(10))

insert into @.t
select 'aaa' union all
select 'bbb' union all
select 'ccc' union all
select 'ddd' union all
select 'eee' union all
select 'fff'

select top 1 a.* from
(select top 2 * from @.t order by item desc) a
order by item asc

Your query is working fine...i am getting what i want..But i can create a table variable for a existing table..and how can run your query on a existing table without insertion of new data?

Thanks|||it's just an example. do you understand what the example is doing?

just alter the query to target your table instead of @.t, and alter "item" to whatever column you want to order by.|||-It is retrieving only row 1 based on the primary key of the table.I am not willing to use primary key.

Thanks

that was meant to be a little joke. you probably don't know much sql if you thought that might give you what you wanted. :)

you might want to spend some time learning SQL better.|||when i "select * " it is retrieving always a some order (but this order is same for all times) no it isn't

it only appears to be the same order every time

it might even actually be exactly the same order, many times in a row

but without an ORDER BY clause, there is no guarantee of any order in the results