Showing posts with label defined. Show all posts
Showing posts with label defined. Show all posts

Monday, March 26, 2012

How to determine sp caller current database?

When executing a stored procedure that is defined in another database, as:

USE db1;

EXEC db2.dbo.sproc;

Is there a way in the stored procedure "sproc" to determine that the caller made the call from db1?

If nothing else, you can use CONTEXT_INFO to retain that information.

To call the stored procedure you can do something like:

Code Snippet

USE db1;

declare @.binVar varbinary(128)
set @.binVar = convert(varbinary(128), 'db1')
set context_info @.binVar

EXEC db2.dbo.sproc;

and to fetch the information from within the stored procedure you can use something like:

Code Snippet

convert(varchar(128), context_info())

( This is assuming that db_name() is not working for you. )

sql

Wednesday, March 7, 2012

How to delete rows in a table when no primary key is defined

Hello,

I want to delete duplicate rows in a table when no primary key is
defined.
For eg: If we have table1 with data as below,

Suma 23 100
Suma 23 100

I want to delete a row from this table and retain only one row.

I tried deleting self joins and exists operator. But it is deleting
both the rows. I want to retain one row.

Can anybody help me out.

Thanks in advance,
Suma

--
Posted using the http://www.dbforumz.com interface, at author's request
Articles individually checked for conformance to usenet standards
Topic URL: http://www.dbforumz.com/General-Dis...pict221110.html
Visit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbforumz.com/eform.php?p=760520Add a identity column to the table and delete the row with de min value.|||Patarroxa wrote:
> Add a identity column to the table and delete the row with de min
> value.

Or copy the data with a SELECT DISTINCT into another table, drop the
original and rename the new table.

robert|||Create a new table (with a key), then use SELECT DISTINCT or GROUP BY to
populate it from the old one.

--
David Portas
SQL Server MVP
--|||"suma" wrote:
> Hello,
> I want to delete duplicate rows in a table when no primary key
> is defined.
> For eg: If we have table1 with data as below,
> Suma 23 100
> Suma 23 100
> I want to delete a row from this table and retain only one
> row.
> I tried deleting self joins and exists operator. But it is
> deleting both the rows. I want to retain one row.
> Can anybody help me out.
> Thanks in advance,
> Suma

Thanks for the response.
But it has to be done using a single sql statement.
Using multiple we can do it...is there any way to do using a single
sql statement.
Thanks,
Suma|||First of all this is not a table by definition. A table must have a
key. And the answer is No, it will take more than one statement to
clean up the base table -- either a cursor, an IDENTITY or a SELECT
DISTINCT. You can put the SELECT DISTINCT into a VIEW as a kludge.

You did fire the guy that did this, didn't you?|||Using a single DELETE statement it can't be done if there is no way to
differentiate between the rows. That's why a primary key is supposed to
be mandatory. Why should you have a table without a key?

--
David Portas
SQL Server MVP
--|||You're not really saving anything doing it this way over the alternatives,
and it's *very* slow for large numbers of duplicates.

SET ROWCOUNT=1

DELETE table1
WHERE EXISTS (SELECT *
FROM table1 AS t2
WHERE table1.col1 = t2.col1 and table1.col2 = t2.col2 and table1.col3 =
t2.col3
GROUP BY t2.col1, t2.col2, t2.col3
HAVING COUNT(*) > 1)

WHILE @.@.ROWCOUNT>0
DELETE ... --same statement all over

Disclaimer: This is not tested. I am not responsible for any loss of data
incurred by use of this technique. SELECT INTO with GROUP BY is probably
safest and fastest, as recommended by others.

Also see books online, Index, DELETE (described), and the description of
DELETE FROM table WHERE CURRENT OF cursor_name

"suma" <DoNotEmail@.dbForumz.com> wrote in message
news:4_761872_6b47fee83970ff4272fca067cae7180d@.dbf orumz.com...
> "suma" wrote:
> > Hello,
> > I want to delete duplicate rows in a table when no primary key
> > is defined.
> > For eg: If we have table1 with data as below,
> > Suma 23 100
> > Suma 23 100
> > I want to delete a row from this table and retain only one
> > row.
> > I tried deleting self joins and exists operator. But it is
> > deleting both the rows. I want to retain one row.
> > Can anybody help me out.
> > Thanks in advance,
> > Suma
> Thanks for the response.
> But it has to be done using a single sql statement.
> Using multiple we can do it...is there any way to do using a single
> sql statement.
> Thanks,
> Suma|||And thats why oracle we can delete the duplicate rows using rowid or rownum
and not in sql server. Some unique identity has to be there !!|||True, but with correct design you'll never need to. The problem IS
soluble in SQL Server too, it's just that SQL Server requires that you
fix things rather than allow you to live with such a kludgy solution.

--
David Portas
SQL Server MVP
--|||>> Oracle we can delete the duplicate rows using rowid or rownum and
not in sql server <<

Yes, Oracle is a sequential file system and a piss-poor RDBMS under the
covers. Parallelism, set processing, and all the other things that
allow a good SQL implmentation to run 4 to 5 orders of magnitude faster
and 80-90% smaller are not available in Oracle and cannot be because of
a horrible architecture. Look up the performance for Nucleus (Sand
Technology) and other VLDB products.|||There is a way to do this, but it will take massive amounts of time to
delete many rows, because the duplicate rows are deleted one row at a
time. It goes like this:

SET ROWCOUNT 1
-- Generate a rowcount > 0
SELECT COUNT(*) FROM MyTable
While @.@.rowcount > 0
Begin
DELETE MyTable
WHERE (
SELECT COUNT(*)
FROM MyTable T1
WHERE T1.Col1 = MyTable.Col1
AND T2.Col2 = MyTable.Col2
) > 1
End
-- don't forget this line!
SET ROWCOUNT 0

Hope this helps,
Gert-Jan

suma wrote:
> Hello,
> I want to delete duplicate rows in a table when no primary key is
> defined.
> For eg: If we have table1 with data as below,
> Suma 23 100
> Suma 23 100
> I want to delete a row from this table and retain only one row.
> I tried deleting self joins and exists operator. But it is deleting
> both the rows. I want to retain one row.
> Can anybody help me out.
> Thanks in advance,
> Suma
> --
> Posted using the http://www.dbforumz.com interface, at author's request
> Articles individually checked for conformance to usenet standards
> Topic URL: http://www.dbforumz.com/General-Dis...pict221110.html
> Visit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbforumz.com/eform.php?p=760520

Sunday, February 19, 2012

How to define token syntax in MSSQL2005 sp1?

There is one token in my Agent Job $WMI(DatabaseName)

Now,I defined this using $(ESCAPE_NONE(WMI(DatabaseName)))

but failed and prompted: Variable WMI(DatabaseName) not found

What should i do for this? thanks

From the updated books online:

For jobs that run in response to WMI alerts, the value of the property specified by property. For example, $(WMI(DatabaseName)) provides the value of the DatabaseName property for the WMI event that caused the alert to run.

So I believe you don't need the ESCAPE_NONE...

|||

If do not add ESCAPE_NONE,prompt "For SQL Server 2005 Service Pack 1 or later, all job steps with tokens must be updated with a macro before the job can run"

Discover In SQL Server 2005 SP1, the SQL Server Agent job step token syntax has changed

url:http://support.microsoft.com/kb/915845

I want to do something for each database just was created,So I could not specifiy the value of database, how to deal with that? thanks

|||

Perhaps the tokens remain disabled?

Because access to Eventlog is not always secured, the alerts are disabled by default. To get the substitutions to work, you should ensure that only members of trusted groups have write permissions to Eventlog, then enable these tokens on the Agent Properties Dialog Alert System tab, or you can set the AlertReplaceRuntimeTokens reg key.

jkh

How to define token syntax in MSSQL2005 sp1?

There is one token in my Agent Job $WMI(DatabaseName)

Now,I defined this using $(ESCAPE_NONE(WMI(DatabaseName)))

but failed and prompted: Variable WMI(DatabaseName) not found

What should i do for this? thanks

From the updated books online:

For jobs that run in response to WMI alerts, the value of the property specified by property. For example, $(WMI(DatabaseName)) provides the value of the DatabaseName property for the WMI event that caused the alert to run.

So I believe you don't need the ESCAPE_NONE...

|||

If do not add ESCAPE_NONE,prompt "For SQL Server 2005 Service Pack 1 or later, all job steps with tokens must be updated with a macro before the job can run"

Discover In SQL Server 2005 SP1, the SQL Server Agent job step token syntax has changed

url:http://support.microsoft.com/kb/915845

I want to do something for each database just was created,So I could not specifiy the value of database, how to deal with that? thanks

|||

Perhaps the tokens remain disabled?

Because access to Eventlog is not always secured, the alerts are disabled by default. To get the substitutions to work, you should ensure that only members of trusted groups have write permissions to Eventlog, then enable these tokens on the Agent Properties Dialog Alert System tab, or you can set the AlertReplaceRuntimeTokens reg key.

jkh

How to define field attribute for a numeric field in SQL table?

I need create a field to store tax rate. I need only 2 decimal points. I defined the field as decimal, precision=5 and scale=2. Does it mean that it can hold value from 0.00 to 999.99?Actually, it should be able to hold from -999.99 through 999.99.

Terri|||True... here comes my really problem. My aspx form always does rounding for me while I update the table. If I enter 0.7 it will become 0 in the table. If I enter 2.7 it will become 3 in the table. What is the trick?|||You'll have to show us your code surrounding the SQL command. It's probably in how your data type is set up in your SQLParameter or something along those lines. There's no trick from a SQL perspective -- a command from Query Analyzer would simply look like this:


UPDATE test SET taxRate = '.7' WHERE ID = 10

Terri|||Try Numeric it will make the rounding problem go away in SQL Server, in .NET search MSDN for Strings and Formating in your language. Numeric is bigger than Decimal. Hope this helps.

Kind regards,
Gift Peddie|||This is how I coded...

First is the class


Namespace BusinessLogicLayer
Public Class Itm
...
Private _PST As Decimal
...
Public Property PST() As Decimal
Get
Return _PST
End Get
Set(ByVal Value As Decimal)
_PST = Value
End Set
End Property
...
...
Public Function Insert() As Boolean
ItmID = Convert.ToInt32(SqlHelper.ExecuteScalar(ConfigurationSettings.AppSettings(Web.Global.CfgKeyConnString), "AddItm", CatID, ItmD1, ItmD2, UOM, UPrice, PSTPcnt, GSTPcnt, Note, MasterItem))
Return ItmID > 0
End Function 'Insert
...
End Class
End Namespace

then page load sub...

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
...
If txtPSTPcnt.Text = "" Then
txtPSTPcnt.Text = "0.07"
End If
...
End Sub

then when the Save button is clicked


Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
...
Itm.PST = CDec(txtPST.Text)
Itm.Insert()
End Sub

Hopefully you have some clue, thx.|||I changed it to numeric and still have the same result.|||Sorry I did not get back to you yesterday, you need code in Custom Numeric Format Strings with using statement from System.globalization. I found some code using the IFormatProvider and ICustomFormatter interfaces on codeproject site. The second link is on MSDN Custom Numeric Format Strings Output Examples table you may have to use DOUBLE datatype in .NET. Hope this helps.

http://www.codeproject.com
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.asp

Kind regards,
Gift Peddie|||Sorry this is the table that show the DOUBLE datatypes human error lol. Hope this helps

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstringsoutputexample.asp

Kind regards,
Gift Peddie|||Thanks a lot. you're very helpful. Since this is my first project on ASP.net and SQL, I can't grap the idea of using the table you refer to. First of all, where do I define "double" and do I put those code in the ASPX.VB? Appreciated.|||The code below should take you closer to what you want, these are part of the .NET Framework Class Library that perform special tasks for you. I don't know books that covers it in VB.NET but in C# the Complete Reference by Herbert Schildt covered it in details in C# not Asp.net. Hope this helps.

NumberFormatInfo.PercentDecimalSeparator Property
[Visual Basic]the effect of changing the PercentDecimalSeparator property.

[Visual Basic]
Imports System
Imports System.Globalization

Class NumberFormatInfoSample

Public Shared Sub Main()

' Gets a NumberFormatInfo associated with the en-US culture.
Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat

' Displays a value with the default separator (".").
Dim myInt As [Double] = 0.1234
Console.WriteLine(myInt.ToString("P", nfi))

' Displays the same value with a blank as the separator.
nfi.PercentDecimalSeparator = " "
Console.WriteLine(myInt.ToString("P", nfi))

End Sub 'Main

End Class 'NumberFormatInfoSample

'This code produces the following output.

'

'12.34 %

'12 34 %

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemglobalizationnumberformatinfoclasspercentdecimalseparatortopic.asp

Kind regards,
Gift Peddie|||Again thanks for your advice, but I can't find data type Double in SQL2000. Did I miss something?|||Gentlmen, I found where the problem occured. It's because the SQL parameter wasn't defined properly. Instead of saying


(
@.PST decimal(5,2)
)

I only typed


(
@.PST decimal
)

Anyway I thank anyone participated in the threat.

How to define a user variable on Execute Sql Task?

Hi everyone,

How to define a Input variable in a Execute Sql Task?

I've defined a User::Inicio variable which contains 4 as value.

In Parameter Mappins it has been defined. Then, I've gone to General->Sql Statement and allocated the following SQL Statement:

UPDATE CARGAPROCESOS SET FECHAULTIMACARGA = [Inicio]

or

UPDATE CARGAPROCESOS SET FECHAULTIMACARGA = [User::Inicio]

Anyway, I'm stuck, both did not work

Thanks in advance for your comments

Enric,

Use an expression in SQlStatementSource property of your Execute SQL task to build your SQL statement:

"UPDATE CARGAPROCESOS SET FECHAULTIMACARGA = " @.[User::Inicio]

Rafael Salas

|||

Hi Rafael,

Thanks for your quick answer but it doesn't work.

[Execute SQL Task] Error: Executing the query "UPDATE CARGAPROCESOS SET FECHAULTIMACARGA = [@.User::Inicio]" failed with the following error: "Parameter name is unrecognized.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Let me know, I can imagine that's a silly thing..

|||

Well, the error talks abour the ResulSet porperty; what is your value for that? what is you set that to None. Also i think you do not need anything in your parameter tab since the SQL statement is being created by the expression

RAfael Salas

|||Rafael is telling you to set an Expression for the SQLStatementSource property and not set the property value directly. Looks like you set the SQLStatementSource directly to "UPDATE CARGAPROCESOS SET FECHAULTIMACARGA = " + @.[User::Inicio]. To set an expression for the SQLStatementSource property click on the Expressions node on the left hand side of the Execute SQL Task Editor dialog.|||

Hi,

You mean you want to use the user variable in your query right?

Refer this:

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

|||Thanks to all of you