Friday, April 24, 2009

ORA-01400: cannot insert NULL into (string)

Cause: An attempt was made to insert a NULL into the column "USER"."TABLE"."COLUMN".

For example, if you enter:


connect scott/tiger create table a (a1 number not null); insert into a values (null);

Oracle returns:


ORA-01400 cannot insert NULL into ("SCOTT"."A"."A1") : which means you cannot insert NULL into "SCOTT"."A"."A1".

Action: Retry the operation with a value other than NULL.

ORA-12154: TNS:could not resolve the connect identifier specified

Cause: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.

Action: - If you are using local naming (TNSNAMES.ORA file):

- Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)

- Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.

- Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.

- Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.

- If you are using directory naming:

- Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).

- Verify that the LDAP directory server is up and that it is accessible.

- Verify that the net service name or database name used as the connect identifier is configured in the directory.

- Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier

- If you are using easy connect naming:

- Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).

- Make sure the host, port and service name specified are correct.

- Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.

Wednesday, April 22, 2009

8152 - String or binary data would be truncated.

Server: Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.

This error happen when I tried to insert a value too long in a varchar or nvarchar
column:

CREATE TABLE TableName_(id VARCHAR(2))
go

INSERT TableName_ VALUES ('Serkan')

Resolution:
1- Most programmers are lazy they prefer not to change code (and introduce bugs)
INSERT bla VALUES (LEFT('123',2))
2 - Here is one way to do it without changing code but by setting ANSI Warnings to off

SET ANSI_WARNINGS OFF
INSERT TableName_ VALUES ('Serkan')
SET ANSI_WARNINGS ON
--set it back on so code following this won't be messed up

ORA-00604: error occurred at recursive SQL level string

Cause: An error occurred while processing a recursive SQL statement (a statement applying to internal dictionary tables).

Action: If the situation described in the next error on the stack can be corrected, do so; otherwise contact Oracle Support.

ORA-01017: invalid username/password; logon denied

Cause: An invalid username or password was entered in an attempt to log on to Oracle. The username and password must be the same as was specified in a GRANT CONNECT statement. If the username and password are entered together, the format is: username/password.

Action: Enter a valid username and password combination in the correct format.

ORA-12638: Credential retrieval failed

Cause: The authentication service failed to retrieve the credentials of a user.

Action: Enable tracing to determine the exact error.

Tuesday, April 21, 2009

MS SQL Server: Disconnect Users From Database with KILL SID (Kill User Session)

You can delete all the active session with the following query.


DECLARE @spid INT
DECLARE @query NVARCHAR(255)

DECLARE processes CURSOR FOR
SELECT spid FROM master..sysprocesses
WHERE dbid = DB_ID('Your_Database_Name')
AND spid != @@SPID
OPEN processes
FETCH NEXT FROM processes
INTO @spid
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'KILLING '+RTRIM(@spid)
SET @query = 'KILL '+RTRIM(@spid)
EXEC(@query)
FETCH NEXT FROM processes
INTO @spid
END
CLOSE processes
DEALLOCATE processes

Monday, April 20, 2009

Unity : Aynı setle farklı veritabanına bağlanmak

Unity'de bir set ile birden fazla veritabanına bağlanılabilir. Birden fazla veritabanına test amaçlı çalışmalarda bağlanılabilir. Bu bağlantıyı yapmak için:
1. Mevcut Logodb.cfg logodb_orj.cfg olarak kopyalanır.
2. Lgconfig.exe çalıştırılır. Test database'ini yolu bu alana girilir.



3. Logodb.cfg dosyasının ismi Spaintest.cfg olarak değiştirilir.
4. Logodb_orj.cfg dosyasının ismi Logodb.cfg olarak değiştirilir.
5. Unity Kısayolu SpainTest olarak kopyalanır ve özelliklerine /DB:Spaintest.cfg eklenir.



Sonuçta her iki kısayol farklı veritabanlarına bağlanacağı için tek bir set ile iki bağlantı yapılmış olur. (Unity2 versiyonu 1.71)

Friday, April 17, 2009

Msg 15281, Level 16, State 1, Procedure sp_send_dbmail, Line 0

ERROR MESSAGE:
Msg 15281, Level 16, State 1, Procedure sp_send_dbmail, Line 0
SQL Server blocked access to procedure 'dbo.sp_send_dbmail' of component 'Database Mail XPs' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Database Mail XPs' by using sp_configure. For more information about enabling 'Database Mail XPs', see "Surface Area Configuration" in SQL Server Books Online.


RESOLUTION:
We have to enable the Database Mail feature on the server. In the SQL Server Management Studio to use Transact SQL to enable Database Mail, execute the following statement.

use master
go
sp_configure ’show advanced options’,1
go
reconfigure with override
go
sp_configure ‘Database Mail XPs’,1
–go
–sp_configure ‘SQL Mail XPs’,0
go
reconfigure
go

Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
Configuration option 'Database Mail XPs' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'show advanced options' changed from 1 to 0. Run the RECONFIGURE statement to install.

HTTP Error 500 - Internal server error in IE

Error Code: 500 Internal Server Error. The request was rejected by the HTTP filter. Contact your ISA Server administrator. (12217)

RESOLUTION:
The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server. Even though the issue is not yours to troubleshoot or resolve, there are a few things you can do:
Retry the web page by clicking the refresh/reload button or trying the URL from the address bar again. Even though the 500 Internal Server Error is reporting a general error on the web site's servers and not your computer, the server error may only be temporary. Trying the page again will often be successful.

Note: If the 500 Internal Server Error message appears during the checkout process at an online merchant, be aware that duplicate attempts to checkout may end up creating multiple orders - and multiple charges! Most merchants have automatic protections from these kinds of actions but it's still something to keep in mind.


Come back later. The 500 Internal Server Error message is one of the most common error message seen when checking out during an online purchase so sales are often disrupted. This is usually a great incentive to resolve the issue very quickly.


If you can't wait any longer for the problem to be resolved or if you'd like to help out, you may want to attempt to contact the webmaster or another website contact and advise them of their server error. The webmaster of most Internet sites can be reached via email at webmaster@website.com, replacing website.com with the actual website name.

Unity : Türlerine göre yıllık kesilen faturaların sayısı

Fatura türlerine göre gruplanmış, bir yıl içinde kesilen faturaların sorgusu aşağıdadır. Kriterleri değiştirerek farklı amaçlarla bu sorguyu kullanabilirsiniz. Sorguda fatura türünü gösteren DBO.Ay_isl fonksiyonu için tıklayınız.

SORGU:

select TRCODE,COUNT(TRCODE) as fatura_sayisi,DBO.Ay_isl('FT',TRCODE) fatura_turu
from LG_108_01_INVOICE GROUP BY TRCODE ORDER BY TRCODE



UNITY : STLINE üzerinde REMAMOUNT ve REMLNUNITAMNT sıfırlanmama sorunu

Logo Unity'de STLINE üzerinde bulunan REMAMOUNT ve REMLNUNITAMNT alanlarında bir çıkış hareketi olduktan sonra normalde sıfır olması gerekirken 2,48689957516035E-14
gibi rakamlar oluşuyorsa bu kayıtların update yapılarak düzeltilmesi gerekir. (Bu sorun 1.71 versiyonunda var) Bu problemden dolayı aynı malzemeye ait çıkış hareketlerinde sorunlar meydana geliyor, hareket veya irsaliye fişleri, malzemeler yeterli miktarda gözükseler bile oluşturulamıyor. Aşağıdaki sorguları kullanarak sorunu giderebilirsiniz.



select REMAMOUNT,REMLNUNITAMNT,* from LG_109_01_SLTRANS WHERE REMLNUNITAMNT < 0.0001 AND REMLNUNITAMNT<>0
--UPDATE LG_109_01_SLTRANS WITH(READPAST) SET REMLNUNITAMNT=0 WHERE REMLNUNITAMNT < 0.0001 AND REMLNUNITAMNT<>0

select REMAMOUNT,* from LG_109_01_SLTRANS WHERE REMAMOUNT < 0.0001 AND REMAMOUNT<>0
--UPDATE LG_109_01_SLTRANS WITH(READPAST) SET REMAMOUNT=0 WHERE REMAMOUNT < 0.0001 AND REMAMOUNT<>0

Unity'de Farklı Dövizler üzerinden Borç Kapatma İşlemleri

Farklı dövizler üzerinden borç kapatma yapılacaksa, kur farkları işlem tarihi ya da ödeme tarihi esas alınarak hesaplatılır. Kur farkının hesaplama şekli ve ödemelerin ne şekilde izleneceği cari hesap kartında Ticari Bilgiler sayfasında belirlenir.

Cari hesap için ödeme İzleme öndeğeri
Borç kapatma işlemlerinin ne şekilde yapılacağı a cari hesap kartında Ticari bilgiler sayfasında Ödeme izleme alanında belirlenir. Ödeme izleme 2 şekilde yapılır.

1. Aynı dövizli işlemlerle: Cari hesaba ait borç takip ve ödemeler tek bir döviz türü üzerinden izlenir. Farklı işlem dövizi üzerinden kaydedilen faturalar ve ödeme hareketleri birbirini kapatamaz. Kapatma işlemi yapıldığında program işlem döviz türleri uyuşmuyor mesajı verir.
2. Değişik dövizli işlemlerle: Farklı işlem dövizi üzerinden yapılan işlemler ve ödemeler birbirini kapatabilir.

How can be used to remove all database pages and clear cache from the memory in SQL Server?

Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache. If observing through SQL Profiler, one can watch the Cache Remove events occur as DBCC FREEPROCCACHE goes to work. DBCC FREEPROCCACHE will invalidate all stored procedure plans that the optimizer has cached in memory and force SQL Server to compile new plans the next time those procedures are run.

Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. DBCC DROPCLEANBUFFERS serves to empty the data cache. Any data loaded into the buffer cache due to the prior execution of a query is removed.

DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS

How do I reduce the size of my MS SQL database?

Shrink the size of the database data and log files.

Syntax
DBCC SHRINKDATABASE ('database' option [,option] ) [WITH NO_INFOMSGS]

DBCC SHRINKDATABASE ('database_id' option [,option] ) [WITH NO_INFOMSGS]

DBCC SHRINKDATABASE (0 option [,option]) [WITH NO_INFOMSGS]

Options:
target_percent
NOTRUNCATE
TRUNCATEONLY

Key:
0 - Shrink the current database

target_percent - Percentage of free space to remain in the database file

NOTRUNCATE - Free space at the end of the data file is not returned to the OS
(pages are still moved)
TRUNCATEONLY - Release free space at the end of the data file to the OS
(do not move pages)
NO_INFOMSGS - Suppress all information messages (severity 0-10)
Only one of the truncate options can be specified - they do not apply to log files.

Example

DBCC SHRINKDATABASE (MyDatabase);

LOGO Unity, STLINE üzerindeki sıfır olan kur bilgisinin update edilmesi

Logo Unity'de, yerel para birimi ile dövizlerin birlikte gösterildiği bazı raporlarda "Divide by zero" hatası alıyorsanız LG_209_01_STLINE tablosunda döviz bilgisinin girilmemesinden kaynaklanan bir sorun olabilir. Aşağıdaki Query, STLINE tablosundaki döviz bilgisi sıfır olan satırların, döviz tablosundan ilgili tarihteki döviz bilgisi alınarak update yapılmasını sağlar. Sorguyu kendi tablolarınıza göre değiştirmelisiniz.


DECLARE @LOGREF INT
DECLARE @DATE DATETIME
DECLARE @RR FLOAT
DECLARE BIRIMKODU CURSOR FOR
SELECT LOGICALREF, DATE_
FROM LG_209_01_STLINE (NOLOCK) WHERE REPORTRATE=0 AND TRCODE IN (2,3,7,8,1,6)
OPEN BIRIMKODU
FETCH NEXT FROM BIRIMKODU
INTO @LOGREF, @DATE
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @RR=RATES1 FROM L_DAILYEXCHANGES (nolock) WHERE CRTYPE=1 AND EDATE =@DATE
UPDATE LG_209_01_STLINE SET REPORTRATE =@RR
WHERE LOGICALREF=@LOGREF
FETCH NEXT FROM BIRIMKODU
INTO @LOGREF, @DATE
END
CLOSE BIRIMKODU
DEALLOCATE BIRIMKODU
GO

ORA-12838: cannot read/modify an object after modifying it in parallel

ORA-12838: cannot read/modify an object after modifying it in parallelIs it a must that i should commit immediately After that delete inorder to avoid that above error.

Resolution:

It is a limitation of parallel DML .

Once a table has been modified by a parallel DML statement, that table cannot be accessed in a subsequent SQL statement (serial or parallel, DML or query) in the same transaction before the transaction is committed.

Please check the following link for other limitations.
http://www.oracle.com/technology/oramag/oracle/05-may/o35dba.html

So you either have to remove the parallel execution, or commit after the delete.

BTW, if you are deleting every row, it's better to truncate the table. Be aware though that truncate is DDL therefore implies a commit in it.

Error Code 10061: Connection refused in Internet Explorer

  • Error Code 10061: Connection refused
  • Background: When the gateway or proxy server contacted the upstream (Web) server, the connection was refused. This usually results from trying to connect to a service that is inactive on the upstream server.

Resolotion:

Problem was resolved by publishing another Web Chaining Rule, to redirect external requests to our ISP's upstream proxy.

Last Default Rule is set to retrieve requests directly

Thursday, April 16, 2009

Reading Information from the LDAP Server with C#

Bring information down from the server and format it into an XmlDocument object. So let's add some variables to our method. I have initialized them to string.Empty and for the instance of AuthenticationTypes, I have initialized it to Anonymous.

string domainAndUsername = string.Empty;
string userName = string.Empty;
string passWord = string.Empty;
AuthenticationTypes at = AuthenticationTypes.Anonymous;


Next we populate the connectivity information with real values:

domainAndUsername = @"LDAP://123.12.12.123/dc=youcanlearnseries,dc=abc.us,dc=com";
userName= "kenno" ;
passWord= "password";
at = AuthenticationTypes.Secure;


Yes, we could have populated this information when we initialized the objects, but if you want to pass in multiple Directory servers, Active Directory, Sun One, etc., then this allows you to create the variable and then populate it later after user input.

Then we create an instance of a DirectoryEntry object. This object encapsulates a node in the Directory Services hierarchy. We pass into the object the connectivity information we created previously.

DirectoryEntry entry = new DirectoryEntry(domainAndUsername,userName, passWord,at);

To actually query the Directory server, we will create an instance of a DirectorySearcher object and we will pass into the DirectorySearcher object the DirectoryEntry object we created in the previous step.

DirectorySearcher mySearcher = new DirectorySearcher(entry);

The results of the query are stored in a collection object, SearchResultCollection, called results.

SearchResultCollection results;

We still want to filter the final results so we add the filter query to the mySearcher object.

mySearcher.Filter = filter;

And finally, we query the LDAP repository, storing the results in the results collection.

results = mySearcher.FindAll();

The rest of the formula is simple yet slightly confusing in its implementation. We have all the information returned for our query of the Directory Server stored in a SearchResultCollection object as a collection of properties and values. We are going to build our own XML object to return to our calling web service. Using a foreach loop, we iterate through the result collection, pulling out properties first and then within each property we find the actual value stored in the hierarchy. The code below has been shortened to show how the loop through the collection works.

foreach(SearchResult resEnt in results)
{
ResultPropertyCollection propcoll=resEnt.Properties;
foreach(string key in propcoll.PropertyNames)
{
foreach(object values in propcoll[key])
{ switch (key)
case "sn":
sb.Append(key.ToString() + ""
+ values.ToString() + "
");
break;
case "cn":
sb.Append(key.ToString() + ""
+ values.ToString() + "
");
break;
case "name":
sb.Append(key.ToString() + ""
+ values.ToString() + "
");
break;
}
}
}
}

The "key" that we need is determined by the LDAP directory you are using. Sun One uses different keys than Microsoft's Active Directory. So the system administrator might be able to inform you of the keys to use for your specific application, or you filter at a higher level and see what keys are returned and break it down yourself.

Each user that we select from our query we are going to wrap in a tag of our XML object. Notice that we create them as a StringBuilder object and then before we send them to the calling object, we load them into an XmlDocument object. We could have created an XML schema and then loaded them into the XmlDocument as we go, but for this example, I felt that was more information than needed.

Tuesday, April 14, 2009

How can I list Locked and inactive sessions in Oracle?

SELECT c.owner, c.object_name, c.object_type,
fu.user_name locking_fnd_user_name,
fl.start_time locking_fnd_user_login_time, vs.module, vs.machine,
vs.osuser, vlocked.oracle_username, vs.SID, vp.pid,
vp.spid AS os_process, vs.serial#, vs.status, vs.saddr, vs.audsid,
vs.process
FROM fnd_logins fl,
fnd_user fu,
v$locked_object vlocked,
v$process vp,
v$session vs,
dba_objects c
WHERE vs.SID = vlocked.session_id
AND vlocked.object_id = c.object_id
AND vs.paddr = vp.addr
AND vp.spid = fl.process_spid(+)
AND vp.pid = fl.pid(+)
AND fl.user_id = fu.user_id(+)
AND c.object_name LIKE '%' || UPPER ('&tab_name_leaveblank4all') || '%'
AND NVL (vs.status, 'XX') != 'KILLED'; --<-change it

Query execution time in Oracle?

Oracle 10g has R1 and R2 (r stands for Release).
I hope you have installed R3 (10.2.0.x)

To sped up the processing you have to do 2 important things:

1. To investigate and possibly to increase the size of SGA components - db_buffer_cache, shared_pool_cache

2. To run the statistics package (as SYS):

CREATE OR REPLACE PROCEDURE compute_statistics IS
BEGIN
dbms_stats.gather_database_stats(cascade=>true);
END compute_statistics;
/

Now either run:

execute compute_statistics;

or schedule once weekly:


set serveroutput on
set linesize 200000
variable x number;
begin
DBMS_OUTPUT.enable(200000);
dbms_job.submit(:x,'compute_statistics;',trunc(sysdate),'trunc(sysdate+7)');
commit;
dbms_output.put_line(TO_char(:x));
end;

How to find last executed queries in Oracle?

select c.spid b1, b.osuser c1, b.username c2, b.sid b2, b.serial# b3,
a.sql_text,b.status
from v$SQLTEXT_WITH_NEWLINES a
, v$session b, v$process c
where a.address = b.sql_address
and a.username='&username'
and b.paddr = c.addr
and a.hash_value = b.sql_hash_value
order by c.spid,a.hash_value,a.piece

Which query is currently executing to debug the database performance?

Open an interactive sql session to the server you are interested in using Sybase Central.

do and sp_who and see who is running queries at the moment.

dbcc traceon(7201)
go

dbcc sqltext(spid) --- where spid is the id of the client running the query you are interested in
go

This will give you the last executed statement. If your data server isn't a busy one, then this may help you in debugging

How to find last executed queries in SQL server 2005?

SELECT deqs.last_execution_time AS [DateTime], dest.text AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC


Monday, April 13, 2009

JavaScript Special Characters in C#

In JavaScript you can add special characters to a text string by using the backslash sign.

Insert Special Characters
The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

Look at the following JavaScript code:

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);


In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called

To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:

var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);


Code Outputs
\' --> single quote
\" --> double quote
\& --> ampersand
\\ --> backslash
\n --> new line
\r --> carriage return
\t --> tab
\b --> backspace
\f --> form feed



Example 2

_List.ListRow.AddColumn("" + GetStatus(_COSTLINE.GetSTATUS()) + " ", "Left", false, "7%");

How to change postgresql Sequence number?

In general you can use the code below to set the value. (similar to
"ALTER TABLE XTable AUTO_INCREMENT = 311" in MsSQL database)

SELECT setval('schemaname.sequencename', 1467);

Thursday, April 9, 2009

The Tabular Data Stream (TDS) version 0x730a0003 of the client library used to open the connection is unsupported or unknown.

Some customers have reported connection failure because of wrong TDS version.
The client application gets the following error message: (or similar depends on the protocol used)

A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)



When you check the errorlog of your SQL Server, you see the following error message:

The Tabular Data Stream (TDS) version 0x730a0003 of the client library used to open the connection is unsupported or unknown. The connection has been closed. [CLIENT: x.x.x.x]

Error: 17802, Severity: 20, State: 1.

Depends on your client version, 0x730a0003 could be 0x73080003 or 0x73090003 as well.

The failure only happens when connecting to SQL Server 2008 CTP releases. Usually the client involved uses SQLClient which is part of .Net Framework. The reason here is that we don't supported connection between intermediate TDS version. SNAC usually ships with SQL Server and they are managed to be in the same TDS level. If you download SNAC CTP separately or make connection across machines with different level of SNAC, you may also see similar error. As a background, for 0x730a0003 TDS version, 73 represents TDS major version 7.3, 0x03 is the minor version for TDS7.3, 0xa is the intermediate TDS version number.

We have shipped the following intermediate TDS version for SQL Server 2008.

· 08 first 7.3 TDS version in Katmai (Shipped with Katmai CTP3 --Jun 2007--, Orcas Beta1)

· 09 TVP (Table Value Parameter) and NewDateTime (Shipped with Katmai CTP4 --build #1049, July 2007--, Orcas Beta2)

· 0A Large UDT (Shipped with Katmai CTP5 --build #1185, Nov 2007--, Orcas RTM, Vista SP1)

· 0B SparseColumn (Shipped with Katmai CTP6 --build #1321 Feb 2008-- )

All .Net Framework 3.5 released after Orcas RTM is on 0x0A TDS level. All SQL Server 2008 release after CTP6 (including RC0 and RTM) is on 0x0B TDS level. Connection can only be made between same TDS intermediate version, with one exception:

0B level of SQL Server can also accept 0A level of client. Thus, Orcas RTM can connect to SQL Server 2008 RTM without problem.

With the mechanism in place, it's fairly easy to tell which client can connect to which server. e.g. connection from Orcas RTM to Katmai CTP4 server would fail.

Orcas RTM contains .Net Framework 3.5. Some words worth to be quoted here: "As with .NET Framework 3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET Framework 2.0 SP1 and .Net Framework 3.0 SP1."


As a final note, you should not see the failure when there is no CTP server or beta version of client involved. Connection between RTM of client and server is always guaranteed.

Expiring a cookie in CSharp

The first thing you need to understand about cookies is this: Cookies carry an expiry date. The second thing you need to understand is this: Expiry dates are the cause of most cookie-related bugs.

Every time you set the Value of a cookie, remember also to set the Expires date. If you fail to do this you will quickly find yourself losing Cookies owing to them having expired immediately when updating them on the client machine or when the browser closes.

When a cookie expires, the client no longer sends it to the server, so you need to make sure that the Expires property of the cookie is always in the future. If you just set a cookie's value then it will create a cookie with Expires set to DateTime.MinValue (01-Jan-0001 00:00).

You can set a cookie's Expires property using any DateTime value (a positive relief after ASP). For example, if you want a Cookie to expire after the user has not been to that part of your site for a week, you would set Expires = DateTime.Now.AddDays(7).

If you want the cookie to be permanent then the temptation is to use DateTime.MaxValue, as I did in the lat version of this article. However, there is a simple gotcha here.

DateTime.MaxValue is precisely 31-Dec-9999 25:59:59.9999999. But Netscape, even at version 7, doesn't cope with that value and expires the cookie immediately. Amazingly, and somewhat annoyingly, investigation showed that Netscape 7 will cope with 10-Nov-9999 21:47:44 but will not handle a second higher (I'll be honest, I didn't test it to any fraction of a second, I really wasn't interested).

Thus if, like me, you subscribe to the "it doesn't have to look pretty on Netscape, as long as it's functional on the latest version" school of thought, always use a date prior to that. A commonly accepted "permanent" cookie expiry date is DateTime.Now.AddYears(30), ie. 30 years into the future. If someone hasn't visited your site for that long, do you really care what the state was last time they were there?

Export and import to Oracle

Prerequisites/Requirements :

exp and imp are utilities present in the $ORACLE_HOME/bin directory and are installed when Oracle is installed. Their prime purpose is to move logical objects out of and into the database respectively - for example dumping all of the tables owned by a user to a single file is achieved using the exp utility. It is important to distinguish between dumping data in this manner and backing up the database which is normally achieved using the rman utility.
Starting with Oracle 10g these two utilities are deprecated and the Oracle recommended alternatives are the data pump versions of these utilities which provide a number of new features including the ability to disconnect and reconnect to an interactive session (so a direct logon to the server isn't required) and improved performance. There are still a number of things that cannot be achieved with the data pump utilities - in particular exporting/importing across a named pipe which is a technique used by database administrators when the export file needs to be compressed on the fly or when one wishes to export directly to an import session.

Before executing these commands, the environment should be set correctly for the user in particular if the examples used on this page are followed the $ORACLE_HOME, $ORACLE_SID and $PATH environment variables need to be set appropriately in a unix environment and the %ORACLE_SID% environment variable needs to be set in a windows environment. If you login as the owner of the oracle software (usually the oracle user on unix) these are likely to have been set in the users profile. The Oracle Database instance needs to be up in order to export/import data. Type 'imp help=y' or 'exp help=y' for a detailed explanation of the available options for these utilities. Some brief examples follow to illustrate the usage of these utilities.


Using exp:

To export the entire database to a single file dba.dmp in the current directory.

- Login to server

exp SYSTEM/password FULL=y FILE=dba.dmp LOG=dba.log CONSISTENT=y
or

exp SYSTEM/password PARFILE=params.dat

where params.dat contains the following information

FILE=dba.dmp
GRANTS=y
FULL=y
ROWS=y
LOG=dba.log

To dump a single schema to disk (we use the scott example schema here)

- Login to server which has an Oracle client

exp / FIlE=scott.dmp OWNER=scott


To export specific tables to disk:

- Login to server which has an Oracle client

exp SYSTEM/password FIlE=expdat.dmp TABLES=(scott.emp,hr.countries)
-the above command uses two users : scott and hr

exp / FILE=scott.dmp TABLES=(emp,dept)
the above is only for one user

Using imp:

To import the full database exported in the example above.


imp SYSTEM/password FULL=y FIlE=dba.dmp

To import just the dept and emp tables from the scott schema


imp SYSTEM/password FIlE=dba.dmp FROMUSER=scott TABLES=(dept,emp)

To import tables and change the owner

imp SYSTEM/password FROMUSER=blake TOUSER=scott FILE=blake.dmp TABLES=(unit,manager)


To import just the scott schema exported in the example above


imp / FIlE=scott.dmp

If you do not supply any parameters then you enter an interactive session as illustrated below.

$>imp
Import: Release 9.2.0.6.0 - Production on Thu Mar 29 15:07:43 2007
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Username: SYSTEM
Password: password
Connected to: Oracle9i Enterprise Edition Release 9.2.0.6.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.6.0 - Production
Import file: expdat.dmp > /mention/path/of/dumpFile/includingFileName.dmp
Enter insert buffer size (minimum is 8192) 30720> (press enter to accept default)
Export file created by EXPORT:V09.02.00 via conventional path
import done in US7ASCII character set and AL16UTF16 NCHAR character set
import server uses AL32UTF8 character set (possible charset conversion)
List contents of import file only (yes/no): no > press enter
Ignore create error due to object existence (yes/no): no > press enter
Import grants (yes/no): yes > press enter
Import table data (yes/no): yes > press enter
Import entire export file (yes/no): no > press enter or type no
Username: give the userName for which you want the data to be imported
Enter table(T) or partition(T:P) names. Null list means all tables for user
Enter table(T) or partition(T:P) name or . if done: press enter
. importing TST_001_V2's objects into TST_001_V2


Good practices

Always take care about CHARSETS when you do export and import. Using the wrong ones can convert your data in a lossy manner. The best situation is when your source and destination database have the same character sets, so you can avoid completely any character conversion. You control this behaviour by setting NLS_LANG environment variable appropriately. When not set properly you may see 'Exporting questionable statistics' messages.
After doing an export, it is better to check your dump by doing an import with the parameter SHOW=Y. This checks the validity of your dump file.

Other considerations

You may need to patch your Oracle client (where you are running exp/imp) to the same level as the Oracle server to prevent errors
When importing large amounts of data consider dropping indexes prior to the import to speed up the process and re-creating them once the import is completed
The amount of archivelogs that may be created on a large import may fill up your disk
On INSERT triggers will fire, consider whether these need to be disabled
Increasing the RECORDLENGTH (max 65535) parameter can improve the length of time to perform an import/export as well as DIRECT=y for export



Referance: http://wiki.oracle.com/page/Oracle+export+and+import+?t=anon

Wednesday, April 8, 2009

SQL Query that search all column names based on criteria

While browsing the SQL Server newsgroups, every once in a while, I see a request for a script that can search all the columns of all the tables in a given database for a specific keyword. I never took such posts seriously. But then recently, one of my network administrators was troubleshooting a problem with Microsoft Operations Manager (MOM). MOM uses SQL Server for storing all the computer, alert and performance related information. He narrowed the problem down to something specific, and needed a script that can search all the MOM tables for a specific string. I had no such script handy at that time, so we ended up searching manually.


That's when I really felt the need for such a script and came up with this stored procedure "SearchAllTables". It accepts a search string as input parameter, goes and searches all char, varchar, nchar, nvarchar columns of all tables (only user created tables. System tables are excluded), owned by all users in the current database. Feel free to extend this procedure to search other datatypes.

The output of this stored procedure contains two columns:

- 1) The table name and column name in which the search string was found
- 2) The actual content/value of the column (Only the first 3630 characters are displayed)

Here's a word of caution, before you go ahead and run this procedure. Though this procedure is quite quick on smaller databases, it could take hours to complete, on a large database with too many character columns and a huge number of rows. So, if you are trying to run it on a large database, be prepared to wait (I did use the locking hint NOLOCK to reduce any locking). It is efficient to use Full-Text search feature for free text searching, but it doesn't make sense for this type of ad-hoc requirements.

Create this procedure in the required database and here is how you run it:

--To search all columns of all tables in Pubs database for the keyword "Computer"
EXEC SearchAllTables 'Serkan SONMEZ'
GO




CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)

WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)

IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END

SELECT ColumnName, ColumnValue FROM #Results
END

[Fatal Error] Internal Error: LA30

Try deleting all .dcu files and the debugger info (.tds?) then forcing a full build (not just compile).

How to Deal With Errors in C++

As a programmer, it's your job to produce robust systems that run smoothly at all times. You don't have to write functions that check flags and return cryptic error codes. Program recovery from a bad situation can be smooth because of a mechanism called C++ Exception Handling. Objects called Exceptions can be "thrown" from the error site and "caught" by an Exception Handler, giving you a chance to set things right.

1.Create an exception class for each base class in your design using a C++ development environment. All can share a common structure. For a File base class create a FileException exception class, for a GameEntity base class create a GameEntityException exception class. Get the pattern?

2.Place the exception class inside the public area of the base class. The exception class has to be visible as it will be called by the handler.

3.Give each exception class a constructor that accepts an input string. The input string will contain the error message that will be displayed when the exception object gets caught by the handler.

4.Create a handler function for each exception class you have designed. Each handler function is an overloaded "catch" function differing in the type of input argument. The first line of the two handlers would look like, "catch(File::FileException* e) {…" and "catch(GameEntity::GameEntityException* e) {…". Place these exception handler functions right underneath 'main.'

5.Inundate your programming space with "throw" statements. Put them in two major areas. Insert "throw" statements where you see potential for trouble, "if (/*divide by zero*/) {throw Math::MathException("division by zero");}. Declare a 'throw' statement on the right of a function or class that calls exceptions, "void Divide(/*parameters*/) throw (Math::MathException) {…".

6.Insert your execution code inside "main," within "try" braces. The C++ exception handling mechanism has a try, throw and catch structure. Not only does this make programs extremely robust but it is pleasant to read

How to Merge ASP With HTML

Merging ASP and HTML enables you to create a dynamic website with a wealth of information.
Below is an illustration of how to create an ASP page for classic ASP and ASP.NET 2.0that show the login credentials of a user.


1.Write the programming language you will use for the ASP code. Your options are VBScript, JavaScript and VB or C# for ASP.NET.

Classic ASP
< %@Language="VBSCript,"

ASP.NET
< %@Page Language="VB," %>

2.Name the HTML Header and part of BODY section
< HTML>
< HEAD>
< TITLE >Login Page< /TITLE >
< /HEAD >

3. Begin the BODY section

< BODY BGCOLOR="White" TOPMARGIN="10" LEFTMARGIN="10" >

< FONT SIZE="4" FACE="ARIAL, HELVETICA" >
< B >Login Page< /B>< /FONT >< BR >

< HR SIZE="1" COLOR="#000000" >

4. Put ASP code within the HTML text


You logged in as user: <%= Request. ServerVariables ("LOGON_USER") %>



< P>You were authenticated using:< B> < %= Request.ServerVariables("AUTH_TYPE")% >< /B> authentication.

5.Insert the closing Tags for BODY and HTML
< /BODY>
< /HTML>

6. Save the file. Use .asp for classic ASP file and .aspx for ASP.NET file.
e.g UserCredential.asp or UserCredential.aspx

PHP vs ASP vs JSP vs ColdFusion vs PERL

CF - I was an expert at it at one time - before java intragration. Costs $$$ - so why use it when there are so many good free ones out. Didn't scale as well as the other languages (when i used it in the past)

PERL - like the pervious guy said - perl is great - but why, when php is faster to develope, learn, and use. (runs faster too)

PHP - its great for small and medium sites. for large - complex sites with complex business logic, jsp/asp.net win hands down. Better tools to reuse logic with those. Runs very fast. the php/MySQL combo is hard to beat. Very stable.

asp - ok, easy to learn, not as easy as CF. Runs faster then CF, slower then PHP. If you don't already know it - move on to .net

asp.net - good web language. The fastest out there and very easy to scale. But again - you have to pay for the OS. Very stable.

JSP - only JSP and asp.net are really fully object oriented and you can reuse your code in websites, serverside apps and client apps. JSP is a little harded to learn (java vs VB) JSP can be fast - but its harder to tune then asp.net. Out of the box - asp.net is faster.

SQL Server vs MySQL vs Oracle vs PostgreSQL

As far as features, performance and power goes, Oracle is leader of the pack clearly. There are more features and tools available for Oracle than for any other DB. However, you will be paying, and paying dearly. You will be able to rest assured that your DB system is the best that money can buy.

Now in most cases, money *is* an object, and as such tradeoffs must be made. In my opinion, PostgreSQL is just below Oracle for powerand features. In fact, there are some things now that PGSQL even do better than Oracle especially in terms of transaction concurrency, PGSQL's MVCC (Multi Version Concurrency Control) model is widely accepted as beign the best conscurrency handling system there is. And its catching up. PGSQL version 8 is due out any day now, there are huge performance increases and features being added in the new version such as native Windows support (it will now install and run on any Win32 system including NT, 2000, XP and 2003), replication in the Slony-I project which brings PGSQL's scaleability to Oracle's calibre.

MySQL is a non-fitter in my opinion. It would be a great product, but since PGSQL's performance has taken great steps in the last few years there is little room for this between PGSQL and SQLite for MySQL to fit in. (SQLite is an ultralightweight, ultrafast SQL database that is embeddable and can be used for small simple projects, and is blisteringly fast in such uses.) MySQL has a *huge* following, and I'm risking a lynching bad mouthing it here, but I personally feel that it is a has-been product with benefits that were once leaders of the pack but have since been overtaken by superior products, namely PostgreSQL and SQLite.

MS SQL is a good product to work with if you're a die hard Windows and Microsoft user and are familiar enough with the other software that goes with it, and are comfortable paying large amounts of money for licences. Personally, with far superior open source options, I feel that MS SQL is a silly choice unless you have your hands tied by other considerations such as licencing constraints or compatibility with other MS products.

Finally, my overall view is that I use SQLite for small projects such as web polls and guestbooks where only the standard SQL commands are sufficient and there is no need for transactions, row/column/table locking, stored procedures and the like. I use PostgreSQL for large projects requiring transactions, stored procedures and with replication I cannot see myself involved in anything too big for PG. In fact I can't think of anything outside genetics and other highly specialised fields where PG would not suffice.

Finally, PG is distributed under the BSD licence, which means there is no chance of licencing compliance issues in your application, and you are guaranteed that there will never be any costs associated with the use of the DB itself.

List of all Tables in Sybase

CREATE TABLE #TT (IDENT NUMERIC(12) IDENTITY,
...... all the rest of your columns in your result set...)

SELECT ob.name as ParentProc, bo.name as ChildProc, bo.type as ChildType
INTO #procdepends
FROM sysdepends dp
JOIN sysobjects ob ON ob.id = dp.id
JOIN sysobjects bo ON bo.id = dp.depid
WHERE ob.type = 'P' AND bo.type = 'P'

INSERT INTO #TT
select pd1.ParentProc as Root, isnull(pd1.ChildProc,'') as Level1,
isnull(pd2.ChildProc,'') as Level2,
isnull(pd3.ChildProc,'') as Level3, isnull(pd4.ChildProc,'') as Level4,
isnull(pd5.ChildProc,'') as Level5
from #procdepends pd1
left outer join #procdepends pd2
on pd2.ParentProc = pd1.ChildProc
left outer join #procdepends pd3
on pd3.ParentProc = pd2.ChildProc
left outer join #procdepends pd4
on pd4.ParentProc = pd3.ChildProc
left outer join #procdepends pd5
on pd5.ParentProc = pd4.ChildProc
left outer join #procdepends pd6
on pd6.ParentProc = pd5.ChildProc
where pd1.ParentProc not in (select ChildProc from #procdepends)
order by pd1.ParentProc, pd1.ChildProc,
pd2.ChildProc, pd3.ChildProc,
pd4.ChildProc, pd5.ChildProc,
pd6.ChildProc

SELECT CASE WHEN A.ROOT = B.ROOT THEN '' ELSE A.ROOT END AS ROOT,
CASE WHEN A.LEVEL1 = B.LEVEL1 THEN '' ELSE A.LEVEL1 END AS LEVEL1,
............ the rest of your levels the same way....
FROM #TT A -- Current record
LEFT OUTER JOIN #TT B -- Prior record
ON A.IDENT = B.IDENT + 1

Table Counts on SQL Server

DECLARE @SQL nvarchar(2000),
@TableName sysname,
@TableCount integer

Declare @TableCounts table(TableName sysname, TableCount integer)

SET NOCOUNT ON

DECLARE TableCursor CURSOR FOR
SELECT name from sysobjects WHERE xtype = 'U' ORDER BY 1

OPEN TableCursor

FETCH NEXT FROM TableCursor
INTO @TableName

WHILE @@FETCH_STATUS = 0
BEGIN
Set @SQL = N'SELECT @TableCountOut = COUNT(*) FROM [' + @TableName + ']'
exec sp_executesql @SQL, N'@TableCountOut integer output', @TableCount output
Insert @TableCounts (TableName, TableCount) Values (@TableName, @TableCount)
FETCH NEXT FROM TableCursor
INTO @TableName
END

CLOSE TableCursor
DEALLOCATE TableCursor

Select * From @TableCounts



Can I find past queries from the sysobjects table?

Questions:
Is there any way to look in logs, or to set up logs, that will track historical queries into the sysobjects table? The intruders seem to always be going after this table first to find our schema - is there any way to tell when a query was directed against that table?

Resolutions:
Profiler would work for future statements only...but it would work great for them. But... you're not going to be able to get at the past select statements

Do not run stored procedure if file does exist using sysobjects

if not exists (SELECT * FROM Warehouse..sysobjects WHERE name = 'sales' and convert(varchar, crdate, 102) = CONVERT(varchar, GETDATE(), 102)) goto ExitHere

Sysobjects equivalent in PostgreSQL?

Foreign keys can be queried like this:

select t.constraint_name, t.table_name, t.constraint_type,
c.table_name, c.column_name
from information_schema.table_constraints t,
information_schema.constraint_column_usage c
where t.constraint_name = c.constraint_name
and t.constraint_type = 'FOREIGN KEY'
and c.table_name = 'mytable';

DB Status in SQL Server : Indicates the number of records of all databases objects. (Stored procedure, User Table, Indexes)

DECLARE @db_name AS varchar(100)
DECLARE @sql AS nvarchar(1000)
DROP TABLE #DB_Stats
CREATE TABLE #DB_Stats (
dbname varchar(100),
Description varchar(100),
Total_count int)

DECLARE cur_DB_Names CURSOR FOR
SELECT name FROM master..sysdatabases

open cur_DB_Names

Fetch next from cur_DB_Names into @DB_name

WHILE @@fetch_status =0
begin

SET @sql= 'insert into #DB_Stats(dbname, description, total_count) select '''+@DB_name + ''',''User_table'', count(*) from [' + @DB_name + ']..sysobjects where xtype = ''U'''
exec sp_executesql @sql
SET @sql= 'insert into #DB_Stats(dbname, description, total_count) select '''+@DB_name + ''',''indexes'', count(i.name) from [' + @DB_name + ']..sysobjects n join [' + @DB_name + ']..sysindexes i on (n.id = i.id) where n.xtype = ''U'''
exec sp_executesql @sql
SET @sql= 'insert into #DB_Stats(dbname, description, total_count) select '''+@DB_name + ''' ,''V'',count(*) from [' + @DB_name + ']..sysobjects where xtype = ''V'''
exec sp_executesql @sql
SET @sql= 'insert into #DB_Stats(dbname, description, total_count) select '''+@DB_name + ''' ,''P'',count(*) from [' + @DB_name + ']..sysobjects where xtype = ''P'''
exec sp_executesql @sql
SET @sql= 'insert into #DB_Stats(dbname, description, total_count) select '''+@DB_name + ''' ,''DTS'',COUNT(distinct cast(id as varchar(128))) from [msdb]..sysdtspackages'
exec sp_executesql @sql
Fetch next from cur_DB_Names into @DB_name
end

CLOSE cur_DB_Names
deallocate cur_DB_Names

SELECT * FROM #db_stats


Tuesday, April 7, 2009

String Format for Double [C#]

String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.
Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.

// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.

// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point
If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.

// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"

Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.

String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"

Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).

String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces
To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.

String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.

String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples
As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.

String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

ORA-06502: PL/SQL: numeric or value error string

Cause: An arithmetic, numeric, string, conversion, or constraint error occurred. For example, this error occurs if an attempt is made to assign the value NULL to a variable declared NOT NULL, or if an attempt is made to assign an integer larger than 99 to a variable declared NUMBER(2).

Action: Change the data, how it is manipulated, or how it is declared so that values do not violate constraints.

ORA-04932: increment or adjust of sequence number failed

Cause: A call to the SSN failed to increment the sequence number.

Action: Verify that the MC hardware is functioning properly. If it is not, contact Digital"s customer support organization. If it is, contact Oracle support.

ORA-04931: unable to set initial sequence number value

Cause: A call to the SSN failed to set the sequence number to its initial value, possibly caused by an MC hardware problem.

Action: Verify that the MC hardware is functioning properly. If it is not, contact Digital"s customer support organization. If it is, contact Oracle support.

ORA-04930: open sequence number failed or initial state is valid

Cause: Either Shared Sequence Number OS component was not installed properly, or an MC hardware failure may have occurred or a previous instance was not shut down properly.

Action: Verify that there are no background or foreground Oracle processes from a previous instance on this node using the OS command ps -ef|grep . Verify that there are no shared memory segments belonging to the user which owns the Oracle installation by isuing the ipcs -b OS command. If there are shared memory segments or processes still on the system, use svrmgrl to shutdown the instance with the abort option. If the instance is not up, verify that the cluster software and/or the hardware is installed and working. Log in as superuser and issue the cnxshow command. Are all of the nodes in the cluster listed? Are they members of the cluster? Is the communications between nodes okay? If the answer to any of these questions is false, contact Digital"s customer support organization.

Disable all jobs on a SQL Server

Have you ever needed to quickly disable all jobs on a SQL Server? If you have a lot of jobs to disable, then this stored procedure will help you out. We move our systems to our disaster recovery site twice per year for disaster recovery testing. As part of this process, we need to disable all jobs on our SQL Servers. It doesn't take a whole lot of time to do this inside Enterprise Manager, but when your goal is to complete your work quickly so that the customer impact is minimal, you want to save all of the seconds that you can.

CREATE PROC isp_Disable Jobs
AS
SET NOCOUNT ON
CREATE TABLE #Job_Names
(
Job_Name SYSNAME NOT NULL
)
INSERT INTO #Job_Names

SELECT name
FROM msdb.dbo.sysjobs
ORDER BY name
DECLARE @job_name SYSNAME
DECLARE @job_id UNIQUEIDENTIFIER
DECLARE disable_jobs CURSOR FOR
SELECT Job_Name
FROM #Job_Names
SET @job_id = NULL
OPEN disable_jobs
FETCH NEXT FROM disable_jobs INTO @job_name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC msdb.dbo.sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT
EXEC msdb.dbo.sp_update_job @job_id, @enabled = 0
SET @job_id = NULL
FETCH NEXT FROM disable_jobs INTO @job_name
END
CLOSE disable_jobs
DEALLOCATE disable_jobs
DROP TABLE #Job_Names
RETURN

If you want to quickly enable all jobs, just change @enabled = 0 to @enabled = 1. Change the stored proc name as well so that it makes sense.

Monday, April 6, 2009

How can I list a stored procedures in SQL Server?

use [AustriaUnity]
GO
select [Object_id],[name],[type_desc] from sys.objects where type='P' and [name] LIKE '%%'


How to get ID of element that triggered an event with class name

function overfade(evnt)
{
var obj = Event.element(evnt);
alert(obj.id);
}

Return characters only on key press event in JavaScript

Question:
How can I return only character to be entered A-Z a-z on key press event . Restrict numbers and other key using javascript

Resolution:
< script>
function char(e) {
e = (e)?e:window.event;
key = String.fromCharCode(e.keyCode);
if (key.match(/[a-zA-Z]/)) return true;
e.returnValue=null
return false

}
< /script>
< input onkeydown="return char(event)">

How to Convert Unix Epoch to Datetime in MS SQL

This article will demonstrate an easy way to convert an Integer Field that stores an UNIX Epoch number into a Human readable DATETIME value. This is very important when dealing with data imported from UNIX systems. This article will use a temp table to effectly demonstrate the use of the query funtion.


1. Example using MS SQL Server Management Studio Open a SQL Query window Using MS SQL Server Management Studio or your preferred SQL Query Tool to a database which you have access.

2. Execute the following to setup the table and data required for the deminstration;

* Create a TEMP Table in MS SQL by running the following;
* CREATE TABLE #tmp_epoch_test (unix_epoch_time INT);
* Insert a known value to test retreive later;
* INSERT INTO #tmp_epoch_test VALUES (1232648493);

3. Execute the following to return the DATETIME, human readable format;

* SELECT Dateadd(ss, unix_epoch_time,'19700101')
* FROM #tmp_epoch_test;

Returned Results should be: "2009-01-22 18:21:33.000"

4. Execute the following to remove the TEMP TABLE;

DROP TABLE #tmp_epoch_test

How to enable and disable advance options and Ole Automation Procedures in SQL Server 2005

The system stored procedures in SQL Server are very useful. You can find a system stored procedure to do almost any task. However, in order to use these stored procedures, you need to enable Ole Automation Procedures.

In SQL Server 2005, the option is disabled by default.

You might recieve an error similar to the following

SQL Server blocked access to procedure 'sys.sp_OACreate of component 'Ole Automation Procedures

if you are trying to use the Ole Automation Procedures and the option is turned off.

You will need to enable advance options before enabling Ole Automation Procedures.





1. Use the following code to show the current status of advance option and Ole Automation procedure status.

-- Show Advance Options, 0 = disabled, 1 = enabled
EXEC sp_configure 'show advanced options';
GO

-- Show Ole Automation Procedures, 0 = disabled, 1 = enabled
EXEC sp_configure 'Ole Automation Procedures';
GO

2. Use the following code to enable the advance option and Ole Automation Procedures.

-- Enable the Advance options if they are not already turned on
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO

-- Enable the Ole Automation Procedures
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

3. Use the following code to disable the advance option and Ole Automation Procedures.

-- Disable the Advance options
sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO

-- Disable the Ole Automation Procedures
sp_configure 'Ole Automation Procedures', 0;
GO
RECONFIGURE;
GO

How to find the disk size of a table in Microsoft SQL Server

1.Connect to the SQL server instance. Depending on what I'm doing, I usually use SQL Management Studio, or my own custom script / application.

2.Execute "sp_spaceused". As you can imagine there are a few commands that will allow you to figure out your table size. I prefer "sp_spaceused".

usage: "sp_spaceused 'Name of your table'"
example: "sp_spaceused 'user_accounts'"

Yes, the table name is treated like a varchar / string for this command. Something else to keep in mind is that this particular procedure looks at the [sysindexes] system table. There are instances where this table can become a little out of sync; like right after an index is dropped. To compensate for this, there is an optional parameter that you can add to force the recalculation before execution. Just simply add a "true" to the end.

example: "sp_spaceused 'user_accounts', true"

For reference, the true simply forces the system to recalculate by executing "dbcc updateusage (0)" for all the tables, or "dbcc updateusage ('Name of your table')" for a specific table.

3. Analyze the results. The data returned includes the "name", "rows", "reserved", "data", "index_size", and "unused".

- "name", the name of the table.
- "rows", the number of records in the table.
- "reserved", the amount of space currently allocated for the table.
- "data", the current space used by the table's data.
- "index_size", the current size of the table's indexes.
- "unused", the amount of unused space reserved for the table.

Unity : Satış fiyat kartlarının bitiş tarihini değiştirmek

UPDATE LG_208_PRCLIST SET ENDDATE='20101231' WHERE VALUE='20081231'

Unity : Faturası olmayan irsaliyeden F işaretini kaldırmak

Faturası olmayan irsaliyeden F işaretini kaldırmak için aşağıdaki query'ler kullanabilirsiniz.

1) Seçmek için;
SELECT * FROM LG_208_01_STFICHE WHERE BILLED=1 AND INVOICEREF NOT IN (SELECT LOGICALREF FROM LG_208_01_INVOICE)

2) Düzeltmek için;
UPDATE LG_208_01_STFICHE SET BILLED=0 WHERE BILLED=1 AND INVOICEREF NOT IN (SELECT LOGICALREF FROM LG_0208_01_INVOICE)

Named Pipes Provider, error: 40 - Could not open a connection to SQL Server

Check these ;

a) Typo in instance name or wrong instance name. The instance name is not the one you are targeting.
b) Target SQL Server is not running
c) Named Pipe is not enabled on the server. In this case, the SQL server is not listenning on the specific pipe name.

ORA - 12514 :TNS the listener could not solve the SERVICE_NAME appearing in the descriptor of connection

If the SERVICE_NAME parameter is used, the methods below will assist you in
successfully implementing it in the TNSNAMES.ORA file:

1. Use the GLOBAL_DBNAME parameter in the LISTENER.ORA for each SID that you
wish to identify as a separate service. Use the value of this parameter as
the value of the SERVICE_NAME parameter. Of course, any changes made to the
LISTENER.ORA to accomplish this will need to be made active by stopping and
then restarting the listener process.

2. Use the values of the parameters existing in the INIT.ORA, namely
SERVICE_NAMES and DB_DOMAIN to ascertain the value of the SERVICE_NAME that
should be used in the TNSNAMES.ORA. The valid construction of this value is
. with the dot "." separating the two INIT.ORA
values. If your SERVICE_NAMES=BIKES and your DB_DOMAIN=COM, then your
SERVICE_NAME=SONMEZ.COM

3. If you do not have a DB_DOMAIN parameter set in your INIT.ORA, or a
GLOBAL_DBNAME in the LISTENER.ORA, then you can simply use the SERVICE_NAMES
from the INIT.ORA in your TNSNAMES.ORA for parameter SERVICE_NAME.
EXAMPLE:
INIT.ORA contains:
service_names = "UNITY"
db_domain not set

Then Tnsnames.ora entry is:
(CONNECT_DATA =(SERVICE_NAME = "UNITY"))

4. If you have multiple values specified in the SERVICE_NAMES parameter
in the init.ora then use one of them
If SERVICE_NAMES is not set then db_name.db_domain parameters from
INIT.ORA file can be used.

5. If SERVICE_NAMES and DB_DOMAIN is not set in the init.ora or a
GLOBAL_DBNAME in the LISTENER.ORA,then your SERVICE_NAME
in Tnsnames.ora file will be DB_NAME

ORA 27102 - out of memory

Problem:
ORA 27102 - out of memory

Resolution:
It seems you are in Unix/Linux environment. In this case the SWAP partition of your computer should be 3 times the RAM or if the RAM is 1GB the swap can be 2GB.
If you are in Windows you have to provide also TEMP environment variable and ensure enough disk space for swapping.

Check your physical memory:

In Windows:
go through TASK manager->performance

in UNIX:

$ sysdef grep mem
$sysdef grep swap

in Linux:

$ cat /proc/meminfo

ORA:00571 insufficient privileges

Start SQL*Plus and then connect with SYSDBA privileges to the database containing the recovery catalog:
% sqlplus "sys/change_on_install as sysdba"
Create a user and schema for the recovery catalog:
SQL> CREATE USER rman IDENTIFIED BY rman
2 DEFAULT TABLESPACE tools
3 TEMPORARY TABLESPACE temp
4 QUOTA UNLIMITED ON tools;

User created.
Grant the RECOVERY_CATALOG_OWNER role to the schema owner. This role provides the user with privileges to maintain and query the recovery catalog:
SQL> GRANT RECOVERY_CATALOG_OWNER TO rman;

Grant succeeded.
Grant other desired privileges to teh RMAN user:
SQL> GRANT CONNECT, RESOURCE TO rman;

Grant succeeded.
After creating the catalog owner you should now create the catalog itself by using the CREATE CATALOG command within the RMAN interface. This command will create the catalog in the default tablespace of the catalog owner. you will need to connect to the database that will contain the catalog as teh catalog owner as follows:
% rman catalog rman/rman@catdb

Recovery Manager: Release 9.2.0.1.0 - Production

Copyright (c) 1995, 2002, Oracle Corporation. All rights reserved.

connected to recovery catalog database
recovery catalog is not installed
Now, run the CREATE CATALOG command to create the catalog. Note that this process can take several minutes to complete.
RMAN> create catalog;

recovery catalog created

Oracle Error: -2147467259 (80004005); Provider Error: 0 (0)

Problem:
I have an intermittent error with a SQL200 DTS package that makes a connection to an Oracle server.:

Error: -2147467259 (80004005); Provider Error: 0 (0)
Error string: Oracle error occurred, but error message could not be retrieved from Oracle.
Error source: Microsoft OLE DB Provider for Oracle

The package is executed within a scheduled stored proc.
SET @strSQL = 'master.dbo.xp_cmdshell "dtsrun /S ' + @Server + ' /E /N dtspackagename"'

When the package does fail, I can open it up in the package designer, open up the transformation task and hit the destination tab.. Boom, the same error as above. I then open the connection properties/properties button and test the connection(Test runs fine), and everything works the next couple of times the package runs.. But not for long.

BTW- SQLSERVERAGENT is running under an admin account, SQL 2000 sp-2 and using MS OLE DB Provider for Oracle for a connection/within the package. Oh, and MDACVer 2.71.
What can I do?
Resolution:
I had the same problem and found that using Oracle's driver is better then Microsoft's. If you install the Oracle Client Tools on your SQL Server, you will be able to select "Oracle Provider for OLE DB" when you create your DTS connection objects in the package designer.

How i can update data in the tables present in Oracle using Sql stored procedure?

In ms sql server, you can create linked servers that point to Oracle databases. check out the sp_addlinkedserver stored procedure, and the OPENQUERY() function in the books online.
You can also insert, update and delete using the openquery function...

Oracle 12560 tns error

If you are on Windows start the Oracle Services:
Listener
OracleserviceSID

As Administrator of the machine.
Also the installation of Oracle should be done as Administrator.

If this is Unix:

% lsnrctl start

and to tray to start the instance over SQl*Plus

You need to do this as Oracle user.


If you need remote access do static registration:

Backup LISTENER.ORA file!!!!!!!

In ...\network\admin open listener.ora

see

SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = D:\Ora10g)
(PROGRAM = extproc)
)
(SID_DESC =
(SID_NAME = test)
(ORACLE_HOME = D:\Ora10g)
)
)

Add the entry
(SID_DESC =
(SID_NAME = test)
(ORACLE_HOME = D:\Ora10g)
)
with regard to the particular Oracle Home and SID Name.

Restart the listener:
c:>lsnrctl stop
c:>lsnctl start

Friday, April 3, 2009

Cannot resolve the collation conflict between "Latin1_General_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.

Problem:

select name from sysusers where name not in ( select name from master..syslogins )

Microsoft SQL Server 2005 - 9.00.1399.06 (X64)
Oct 14 2005 00:35:21
Copyright (c) 1988-2005 Microsoft Corporation
Standard Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
(1 row(s) affected)

Msg 468, Level 16, State 9, Line 1
Cannot resolve the collation conflict between "Latin1_General_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.


Resolution:

This is because your master is in a different collation than your user database.
Try adding the COLLATE to your query.

select name from sysusers where name not in ( select name COLLATE Latin1_General_CI_AI from master..syslogins )

Visual Studio CSharp - Exception tips?

You can catch the type 'Exception' and EVERY exception will be caught. If you want to handle multiple exceptions in a different way, you could catch specific exceptions.
For example
try{ ... }
catch(FileNotFoundException ex)
{ // add some code that will create a default file }
catch(ArgumentException ex)
{ // add different code to handle this exception }
catch(Exception ex)
{ // do something with the rest of the exceptions }

In the above example, if a FileNotFoundException occurs, the first catch clause will run, and if some unknown exception occurs that you didn't see coming, it will be caught in the last clause (Exception ex).

ASP .NET: Visual Studio 2005 Generating Error:

Error :

Could not load file or assembly 'RichChart.RichChart, Version=1.0.128.0, Culture=neutral, PublicKeyToken=9de888868d1712bc' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)

Resolution:

First make sure that the virtual directory is an application byright clicking virtual directory and select propertieson virtual directory tab make sure application is not grayed out if so create application.

Second is the folder that contains the source not actually on the server? Is it on the xp workstation if so take a look at this article on creating a code trust between the server and the workstation.
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320268

Clear Cookie in ASP.NET

Delete all cookies:

VB.NET:

Dim i As Integer
Dim cookieName As String
Dim limit As Integer = Request.Cookies.Count - 1
For i = 0 To limit
aCookie = Request.Cookies(i)
aCookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(aCookie)
Next


C#:

private int i;
private string cookieName;
private int limit = Request.Cookies.Count - 1;
for (i = 0; i <= limit; i++)
{
aCookie = Request.Cookies[i];
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

ORA-03114 not connected to ORACLE

Cause: A call to Oracle was attempted when no connection was established. Usually this happens because a user-written program has not logged on. It may happen if communication trouble causes a disconnection. In addition, this message could occur when ALTER SYSTEM KILL SESSION or ALTER SYSTEM DISCONNECT SESSION were issued with the IMMEDIATE qualifier because, in those cases, the client's connection to the database is terminated without waiting for the client to issue a request.

Action: Try again. If the message recurs and the program is user written, check the program.

Thursday, April 2, 2009

How is it possible to make sql server query to ignore locked rows ?

Readpast is the sql server 2005 (new) notation, and has the following difference:

NOLOCK would give you the current value of the row, ignoring locks, possibly giving dirty (uncommitted) data

READPAST would only give you only those rows that are not locked and not dirty (only committed) data

You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels

SQL 2005 error:

"You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels"

Resolution:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SELECT SC.*, A.SiteGuid FROM
dbo.RGSiteConfig SC WITH (READPAST)
INNER JOIN dbo.RGAccount A WITH (READPAST) ON A.AccountGuid = SC.AccountGuid WHERE SiteGuid = @siteGuid

ASCII codes of arrow keys in JavaScript

Left = 37
Up = 38
Right = 39
Down = 40

How can I convert Hex data to ASCII data?

How about IntToHex( Value , NumberOfDigits )

e.g. IntToHex( 260 , 3 ) returns '104'

or

do you mean you've got hex value 0x41 and you want to get the ascii equivalent 'A'

use chr(Value)

e.g. chr( $41 )

Ora 20014

Problem:
I have perform full database restore from my backup. When i try to up the database , I got ora 20014; inconsistent control file. What has causing the error?

Resolution:
This could be because you are using multiple control files and when you restored, you copied to only one location. Check the control_files parameter in init.ora file and make sure that all the files listed match in terms of timestamp, size and contents.

.ora .dbf extension

Questions:
What is difference between .ora and .dbf extension of data file?should i create a data file with .dbf extension?
If I trying to creat a data file using OEM, .ora is the default extension. Why?

Solutions:
The most common naming conventions that I have run across is:
.dbf for database
.log for redo logs
.ctl for control files
.arc for archive logs
.ora for init
.ora file

Ora - 39002, 39070, 39087

PROBLEM:
During datapump import of tables from a schema, so get error code
ora - 39002, 39070, 39087
RESOLUTION:
On destination server, create a Directory, and then grant privilege to the user that you are using to import the data.
SQL> CREATE OR REPLACE DIRECTORY DATA_PUMP_DIR as '/u01/backup/export';
SQL> GRANT read, write ON DIRECTORY DATA_PUMP_DIR TO public;
To export the data, use the following command:
expdp username/password@connectstring
DUMPFILE=abc.dmp LOGFILE=abc.log parfile=/u01/backup/export/exp-query.par
Or in case of import:impdp username/password@connectstring
DUMPFILE=abc.dmp LOGFILE=abc.log parfile=/u01/backup/export/exp-query.par
Where,DUMPFILE is destination dump files (example: expdat.dmp). Please don't specify the full path directory because expdat.dmp should be located under the DATA_PUMP_DIR (which is /u01/backup/export in our example). LOGFILE is Log file name (example: export.log).
Also, log file will be found on DATA_PUMP_DIR (which is /u01/backup/export in our example). PARFILE is the parameter file name (you can specify the full path for this file). Actually, you can specify parameters such as schema, query, parallel, exclude &etc. below is a parameter file sample:
DIRECTORY=DATA_PUMP_DIRDUMPFILE=trdnprd-dump-exp.dmp
LOGFILE=tnngt-test.log
SCHEMAS=tradesuper
QUERY=Schema_Owner.Table_Name:"WHERE 1=2"
exclude=statistics
parallel=2
REMAP_SCHEMA=owner1:owner2

Wednesday, April 1, 2009

Drop table if exists in Oracle ? ORA-00933

DECLARE exists PLS_INTEGER;
BEGIN
select count(*) into exists from user_tables where table_name = 'TableName_';
if exists = 1 then
execute immediate 'drop table TableName_';
end if;
END;

SQL SERVER - Fix : Msg 15151, Level 16, State 1, Line 3 Cannot drop the login ‘test’, because it does not exist or you do not have permission

I got following error when I was trying to delete user ‘test’ with ‘SA’ login. I was little surprised but then I tried to delete with the windows authenticated systemadmin account. Once again I got the same error.

Msg 15151, Level 16, State 1, Line 3Cannot drop the login ‘test’, because it does not exist or you do not have permission.
The reason I was surprised that I was systemadmin and I should be allowed to delete the login. I am including the script which I used to delete the account here.

IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N’Test’)
DROP LOGIN [Test]

Fix/Workaround/Solution:
I finally found out that error was misleading. I had another session open in SQL Server Management Studio with username ‘test’ and it was preventing me to drop the user. Once I closed that open session I was successfully able to delete the user using above script.
In Normal Case:Following error usually show up when user is logged in, which I did not get it.

Msg 15434, Level 16, State 1, Line 3
Could not drop login ‘test’ as the user is currently logged in.

However, when I tried to re-create scenario I got above error. I want to share this experience with users and want to know if they have ever faced this scenario.

Msg 4621, Level 16, State 10, Line 1 Permissions at the server scope can only be granted when the current database is master



ERROR

Msg 4621, Level 16, State 10, Line 1
Permissions at the server scope can only be granted when the current database is master







Fix/Workaround/Solution:

If you look at the database in use is AdventureWorks and when any server level permission has to be granted the database in context should be of master database. Change the database used to master and it should fix the error.



Reference : Pinal Dave (http://blog.sqlauthority.com/)

The FORMAT() Function

The FORMAT() function is used to format how a field is to be displayed.


SQL FORMAT() Syntax
SELECT FORMAT(column_name,format) FROM table_name
Parameter
Description
column_name
Required. The field to be formatted.
format
Required. Specifies the format.


SQL FORMAT() Example
We have the following "Products" table:
Prod_Id
ProductName
Unit
UnitPrice
1
Jarlsberg
1000 g
10.45
2
Mascarpone
1000 g
32.56
3
Gorgonzola
1000 g
15.67
Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD").
We use the following SELECT statement:
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDateFROM Products
The result-set will look like this:
ProductName
UnitPrice
PerDate
Jarlsberg
10.45
2008-10-07
Mascarpone
32.56
2008-10-07
Gorgonzola
15.67
2008-10-07