Msg 6522, Level 16, State 2, Line 1: System.InvalidCastException: Conversion From Type 'SqlBoolean' To Type 'Boolean' Is Not Val
Mar 6, 2008
I created a function called Temperature in VB to be used as a UDF in SQL2005. I get the error listed below. Any thoughts?
CREATE FUNCTION Temperature(@FluidName SQL_variant, @InpCode SQL_variant, @Units SQL_variant, @Prop1 SQL_variant, @Prop2 SQL_variant)
RETURNS Float
AS EXTERNAL NAME Fluids_VB6.[Fluids_VB6.FluidProperties.Fluids].Temperature
Then ran function:
select dbo.temperature('R22','t','e','225.6','0')
Got this:
Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user defined routine or aggregate 'Temperature':
System.InvalidCastException: Conversion from type 'SqlBoolean' to type 'Boolean' is not valid.
System.InvalidCastException:
at Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object Value)
at Fluids_VB6.FluidProperties.Fluids.Setup(Object& FluidName)
at Fluids_VB6.FluidProperties.Fluids.CalcSetup(Object& FluidName, Object& InpCode, Object& Units, Object& Prop1, Object& Prop2)
at Fluids_VB6.FluidProperties.Fluids.CalcProp(Object& FluidName, Object& InpCode, Object& Units, Object& Prop1, Object& Prop2)
at Fluids_VB6.FluidProperties.Fluids.Temperature(Object FluidName, Object InpCode, Object Units, Object Prop1, Object Prop2)
Thanks
Buck
View 1 Replies
ADVERTISEMENT
Jun 3, 2008
This is nutty. I never got this error on my local machine. The only lower case m in the sql is by near the variable Ratingsum like in line 59.
[SqlException (0x80131904): Incorrect syntax near 'm'.An expression of non-boolean type specified in a context where a condition is expected, near 'type'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +196 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +269 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 view_full_article.btnRating_Click(Object Src, EventArgs E) +565 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746</pre></code>
Here is my button click sub in its entirety:
1 Sub btnRating_Click(ByVal Src As Object, ByVal E As EventArgs)
2 'Variable declarations...
3 Dim articleid As Integer
4 articleid = Request.QueryString("aid")
5 Dim strSelectQuery, strInsertQuery As String
6 Dim strCon As String
7 Dim conMyConnection As New System.Data.SqlClient.SqlConnection()
8 Dim cmdMyCommand As New System.Data.SqlClient.SqlCommand()
9 Dim dtrMyDataReader As System.Data.SqlClient.SqlDataReader
10 Dim MyHttpAppObject As System.Web.HttpContext = _
11 System.Web.HttpContext.Current
12 Dim strRemoteAddress As String
13 Dim intSelectedRating, intCount As Integer
14 Dim Ratingvalues As Decimal
15 Dim Ratingnums As Decimal
16 Dim Stars As Decimal
17 Dim Comments As String
18 Dim active As Boolean = False
19 Me.lblRating.Text = ""
20 'Get the user's ip address and cast its type to string...
21 strRemoteAddress = CStr(MyHttpAppObject.Request.UserHostAddress)
22 'Build the query string. This time check to see if IP address has already rated this ID.
23 strSelectQuery = "SELECT COUNT(*) As RatingCount "
24 strSelectQuery += "FROM tblArticleRating WHERE Itemid=" & articleid
25 strSelectQuery += " AND ip = '" & strRemoteAddress & "'"
26 'Open the connection, and execute the query...
27 strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("sqlConnectionString").ConnectionString
28 conMyConnection.ConnectionString = strCon
29 conMyConnection.Open()
30 cmdMyCommand.Connection = conMyConnection
31 cmdMyCommand.CommandType = System.Data.CommandType.Text
32 cmdMyCommand.CommandText = strSelectQuery
33 intCount = cmdMyCommand.ExecuteScalar()
34 intSelectedRating = Int(Me.rbRating.Text)
35 conMyConnection.Close()
36 'Close the connection to release these resources...
37
38 If intCount = 0 Then 'The user hasn't rated the article
39 'before, so perform the insert...
40 strInsertQuery = "INSERT INTO tblArticleRating (rating, ip, itemID, comment, active) "
41 strInsertQuery += "VALUES ("
42 strInsertQuery += intSelectedRating & ", '"
43 strInsertQuery += strRemoteAddress & "', "
44 strInsertQuery += articleid & ", '"
45 strInsertQuery += comment.Text & "', '"
46 strInsertQuery += active & "'); "
47 cmdMyCommand.CommandText = strInsertQuery
48 conMyConnection.Open()
49 cmdMyCommand.ExecuteNonQuery()
50 conMyConnection.Close()
51 Me.lblRating.Text = "Thanks for your vote!"
52 Comments = comment.Text.ToString
53
54 If Len(Comments) > 0 Then
55 emailadmin(comment.Text, articleid)
56 End If
57 'now update the article db for the two values but first get the correct ratings for the article
58 strSelectQuery = _
59 "SELECT SUM(rating) As RatingSum, COUNT(*) As RatingCount "
60 strSelectQuery += "FROM tblArticleRating WHERE Itemid=" & articleid
61 conMyConnection.Open()
62 cmdMyCommand.CommandText = strSelectQuery
63 dtrMyDataReader = cmdMyCommand.ExecuteReader()
64 dtrMyDataReader.Read()
65 Ratingvalues = Convert.ToDecimal(dtrMyDataReader("RatingSum").ToString)
66 Ratingnums = Convert.ToDecimal(dtrMyDataReader("RatingCount").ToString)
67 Stars = Ratingvalues / Ratingnums
68 conMyConnection.Close()
69 'Response.Write("Values: " & Ratingvalues)
70 'Response.Write("Votes: " & Ratingnums)
71
72 UpdateRating(articleid, Stars, Ratingnums)
73 Else 'The user has rated the article before, so display a message...
74 Me.lblRating.Text = "You've already rated this article"
75 End If
76 strSelectQuery = _
77 "SELECT SUM(rating) As RatingSum, COUNT(*) As RatingCount "
78 strSelectQuery += "FROM tblArticleRating WHERE Itemid=" & articleid
79 conMyConnection.Open()
80 cmdMyCommand.CommandText = strSelectQuery
81 dtrMyDataReader = cmdMyCommand.ExecuteReader()
82 dtrMyDataReader.Read()
83 Ratingvalues = Convert.ToDecimal(dtrMyDataReader("RatingSum").ToString)
84 Ratingnums = Convert.ToDecimal(dtrMyDataReader("RatingCount").ToString)
85 Stars = Ratingvalues / Ratingnums
86 If (Ratingnums = 1) And (Stars <= 1) Then
87 lblRatingCount.Text =" (" & (String.Format("{0:f2}", Stars)) & ") / " & dtrMyDataReader("RatingCount") & " Vote"
88 ElseIf (Ratingnums = 1) And (Stars > 1) Then
89 lblRatingCount.Text = " (" & (String.Format("{0:f2}", Stars)) & ") / " & dtrMyDataReader("RatingCount") & " Vote"
90 ElseIf (Ratingnums > 1) And (Stars <= 1) Then
91 lblRatingCount.Text =" (" & (String.Format("{0:f2}", Stars)) & ") / " & dtrMyDataReader("RatingCount") & " Votes"
92 ElseIf (Ratingnums > 1) And (Stars > 1) Then
93 lblRatingCount.Text = " (" & (String.Format("{0:f2}", Stars)) & ") / " & dtrMyDataReader("RatingCount") & " Votes"
94 End If
95
96 'Response.Write(String.Format("{0:f2}", Stars))
97 'Response.Write("Values: " & Ratingvalues)
98 'Response.Write("Votes: " & Ratingnums)
99 If (Stars > 0) And (Stars <= 0.5) Then
100 Me.Rating.ImageUrl ="./images/rating/05star.gif"
101 ElseIf (Stars > 0.5) And (Stars < 1.0) Then
102 Me.Rating.ImageUrl = "./images/rating/05star.gif"
103 ElseIf (Stars >= 1.0) And (Stars < 1.5) Then
104 Me.Rating.ImageUrl = "./images/rating/1star.gif"
105 ElseIf (Stars >= 1.5) And (Stars < 2.0) Then
106 Me.Rating.ImageUrl = "./images/rating/15star.gif"
107 ElseIf (Stars >= 2.0) And (Stars < 2.5) Then
108 Me.Rating.ImageUrl = "./images/rating/2star.gif"
109 ElseIf (Stars >= 2.5) And (Stars < 3.0) Then
110 Me.Rating.ImageUrl = "./images/rating/25star.gif"
111 ElseIf (Stars >= 3.0) And (Stars < 3.5) Then
112 Me.Rating.ImageUrl = "./images/rating/3star.gif"
113 ElseIf (Stars >= 3.5) And (Stars < 4.0) Then
114 Me.Rating.ImageUrl = "./images/rating/35star.gif"
115 ElseIf (Stars >= 4.0) And (Stars < 4.5) Then
116 Me.Rating.ImageUrl = "./images/rating/4star.gif"
117 ElseIf (Stars >= 4.5) And (Stars < 5.0) Then
118 Me.Rating.ImageUrl = "./images/rating/45star.gif"
119 ElseIf (Stars >= 4.5) And (Stars <= 5.0) Then
120 Me.Rating.ImageUrl = "./images/rating/5star.gif"
121 End If
122 dtrMyDataReader.Close()
123 conMyConnection.Close()
124 End Sub
If you want to reduplicate the error, click over here and try to submit a rating:
http://www.link-exchangers.com/view_full_article.aspx?aid=51
Thanks for helping me figure this out.
View 4 Replies
View Related
Nov 16, 2006
hi
I have a float column . only in cursor I get a type missmatch.
does any one knows it ?
the error
Msg 8114, Level 16, State 5, Line 14
Error converting data type varchar to float.
the code
DECLARE @RON_FLOAT FLOAT
DECLARE RON_CURSOR CURSOR FOR
SELECT RON_FLOAT
FROM RON_TABLE1
OPEN RON_CURSOR
FETCH NEXT FROM RON_CURSOR
INTO @RON_FLOAT
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'VALUE IS ' + @RON_FLOAT
FETCH NEXT FROM RON_CURSOR
INTO @RON_FLOAT
END
CLOSE RON_CURSOR
DEALLOCATE RON_CURSOR
the code for the table
CREATE TABLE [dbo].[RON_TABLE1](
[RON_FLOAT] [float] NULL,
[RON_CHAR] [nchar](10) COLLATE Hebrew_BIN NULL
)
View 1 Replies
View Related
Oct 19, 2006
I am trying to put the data from a field in my database into a row in a table using the SQLDataSource.Select statement. I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code, I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.Source Error: Line 54: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'"
Line 55: 'myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments).GetEnumerator.Current, String)
Line 56: myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)
Line 57:
Line 58: filesTable.Rows.Add(myDataRow)Source File: D:YorZapdir_list_sort.aspx Line: 56 Stack Trace: [InvalidCastException: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.]
ASP.dir_list_sort_aspx.BindFileDataToGrid(String strSortField) in D:YorZapdir_list_sort.aspx:56
ASP.dir_list_sort_aspx.Page_Load(Object sender, EventArgs e) in D:YorZapdir_list_sort.aspx:7
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +45
System.Web.UI.Control.OnLoad(EventArgs e) +80
System.Web.UI.Control.LoadRecursive() +49
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3743
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210 Please help me!
View 3 Replies
View Related
May 17, 2006
Dear all,
I am stuck with a SSIS package and I can€™t work out. Let me know what steps are the correct in order to solve this.
At first I have just a Flat File Source and then Script Component, nothing else.
Error:
[Script Component [516]] Error: System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface. at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.HandleUserException(Exception e) at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.AcquireConnections(Object transaction) at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostAcquireConnections(IDTSManagedComponentWrapper90 wrapper, Object transaction)
Script Code (from Script Component):
' Microsoft SQL Server Integration Services user script component
' This is your new script component in Microsoft Visual Basic .NET
' ScriptMain is the entrypoint class for script components
Imports System
Imports System.Data.SqlClient
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Public Class ScriptMain
Inherits UserComponent
Dim nDTS As IDTSConnectionManager90
Dim sqlConnecta As SqlConnection
Dim sqlComm As SqlCommand
Dim sqlParam As SqlParameter
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim valorColumna As String
Dim valorColumna10 As Double
valorColumna = Row.Column9.Substring(1, 1)
If valorColumna = "N" Then
valorColumna10 = -1 * CDbl(Row.Column10 / 100)
Else
valorColumna10 = CDbl(Row.Column10 / 100)
End If
Me.Output0Buffer.PORCRETEN = CDbl(Row.Column11 / 100)
Me.Output0Buffer.IMPRETEN = CDbl(Row.Column12 / 100)
Me.Output0Buffer.EJERCICIO = CInt(Row.Column2)
Me.Output0Buffer.CODPROV = CInt(Row.Column7)
Me.Output0Buffer.MODALIDAD = CInt(Row.Column8)
Me.Output0Buffer.NIFPERC = CStr(Row.Column3)
Me.Output0Buffer.NIFREP = CStr(Row.Column4)
Me.Output0Buffer.NOMBRE = CStr(Row.Column6)
Me.Output0Buffer.EJERDEV = CDbl(Row.Column13)
With sqlComm
.Parameters("@Ejercicio").Value = CInt(Row.Column2)
.Parameters("@NIFPerc").Value = CStr(Row.Column3)
.Parameters("@NIFReP").Value = CStr(Row.Column4)
.Parameters("@Nombre").Value = CStr(Row.Column6)
.Parameters("@CodProv").Value = CInt(Row.Column7)
.Parameters("@Modalidad").Value = CInt(Row.Column8)
.Parameters("@ImpBase").Value = valorColumna10
.Parameters("@PorcReten").Value = CDbl(Row.Column11 / 100)
.Parameters("@ImpReten").Value = CDbl(Row.Column12 / 100)
.Parameters("@EjerDev").Value = CDbl(Row.Column13)
.ExecuteNonQuery()
End With
End Sub
Public Overrides Sub AcquireConnections(ByVal Transaction As Object)
Dim nDTS As IDTSConnectionManager90 = Me.Connections.TablaMODELO80
sqlConnecta = CType(nDTS.AcquireConnection(Nothing), SqlConnection)
End Sub
Public Overrides Sub PreExecute()
sqlComm = New SqlCommand("INSERT INTO hac_modelo180(Ejercicio,NIFPerc,NIFReP,Nombre,CodProv,Modalidad,ImpBase,PorcReten,ImpReten,EjerDev) " & _
"VALUES(@Ejercicio,@NIFPerc,@NIFReP,@Nombre,@CodProv,@Modalidad,@ImpBase,@PorcReten,@ImpReten,@EjerDev)", sqlConnecta)
sqlParam = New SqlParameter("@Ejercicio", Data.SqlDbType.SmallInt)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@NIFPerc", Data.SqlDbType.Char)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@NIFReP", Data.SqlDbType.Char)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@Nombre", Data.SqlDbType.VarChar)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@CodProv", Data.SqlDbType.TinyInt)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@Modalidad", Data.SqlDbType.SmallInt)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@ImpBase", Data.SqlDbType.Decimal)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@PorcReten", Data.SqlDbType.Decimal)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@ImpReten", Data.SqlDbType.Decimal)
sqlComm.parameters.add(sqlParam)
sqlParam = New SqlParameter("@EjerDev", Data.SqlDbType.Decimal)
sqlComm.Parameters.Add(sqlParam)
End Sub
Public Sub New()
End Sub
Public Overrides Sub ReleaseConnections()
nDts.ReleaseConnection(sqlConnecta)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
Thanks a lot for your help
View 13 Replies
View Related
Apr 23, 2007
I get the following message in the vs2005 querybuilder when i do a preview:
***********************************
SQL Execution Error.
Executed SQL statement: SELECT Schoolindex, Variant, VVSchool, [index], indincl, VVRuimtes, School FROM School WHERE (Schoolindex = @PARAM1)
Error Source: SQL Server Compact Edition ADO.NET Data Provider
Error Message: @PARAM1 : Unable to cast object of type 'System.Data.SqlTypes.SqlInt32 to type System.IConvertable'.
****************************************
The same querypreview works fine without the parameter:
SELECT Schoolindex, Variant, VVSchool, [index], indincl, VVRuimtes, School FROM School WHERE (Schoolindex = 186)
Can anybody tell me why this is?
And tell me a way to get the tableadapter working?
Anne-Jan Tuinstra
View 3 Replies
View Related
Jun 19, 2008
I'm getting this error on a vb.net page the needs to execute two separate stored procedures. The first one, is the main insert, and returns the identity value for the ClientID. The second stored procedure inserts data, but needs to insert the ClientID returned in the first stored procedure. What am I doing wrong with including the identity value "ClientID" in the second stored procedure?
Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'.Source Error:
Line 14: If li.Selected Then
Line 15: InsertClientCompanyType.InsertParameters("CompanyTypeID").DefaultValue = li.Value
Line 16: InsertClientCompanyType.InsertParameters("ClientID") = ViewState("ClientID")
Line 17:
Line 18:
Source File: C:InetpubwwwrootIntranetExternalAppsNewEmploymentClientNewClient.aspx.vb Line: 16
Here is my code behind... What am I doing wrong with grabbing the ClientID from the first stored procedure insert?
Protected Sub InsertNewClient_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)ClientID.Text = e.Command.Parameters("@ClientID").Value.ToString()ViewState("ClientID") = e.Command.Parameters("@ClientID").Value.ToString()End SubProtected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit.ClickInsertNewClient.Insert()For Each li As ListItem In CompanyTypeID.Items
If li.Selected ThenInsertClientCompanyType.InsertParameters("CompanyTypeID").DefaultValue = li.ValueInsertClientCompanyType.InsertParameters("ClientID") = ViewState("ClientID")InsertClientCompanyType.Insert()End IfNextEnd Sub
View 2 Replies
View Related
Dec 14, 2005
After testing out the application i write on the local pc. I deploy it to the webserver to test it out. I get this error.
System.Data.SqlClient.SqlException: The conversion of a char data type to a
datetime data type resulted in an out-of-range datetime value.
Notes: all pages that have this error either has a repeater or datagrid which load data when page loading.
At first I thought the problem is with the date, but then I can see
that some other pages that has datagrid ( that has a date field) work
just fine.
anyone having this problem before?? hopefully you guys can help.
Thanks,
View 4 Replies
View Related
Aug 13, 2007
Hi,
I have developed a custom server control for .NET Framework 2.0. The server control has a property named BinaryData of type byte[]. I marked this property to be data bindable. Now, I have varbinary(Max) type of field in my SQL Database and I have used SQLDataSource and bound this varbinary(Max) field with the property BinaryData (byte[]) of my control. It is working fine as long as the data value is not NULL. Now, In my control, I have handled the NULL value so that no Exception is thrown. Still, when I bind this property using the SQLDataSource, I get Error "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'." I am not sure if I can do anything to stop this erro within my control. If it is not possible from the control, then what is the workaround that I can do in my ASPX page in order to stop this error ?
Thanks a lot in advance.
View 10 Replies
View Related
Dec 31, 2007
Hi, I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'." All value for dateSubmitted field are 12/27/2007 12:00:00 AM. cheers,imperialx
View 3 Replies
View Related
Jun 21, 2006
Hi,
I want to create a text file and write to text it by calling its assembly from Stored Procedure. Full Detail is given below
I write a code in class to create a text file and write text in it.
1) I creat a class in Visual Basic.Net 2005, whose code is given below:
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Public Class WLog
Public Shared Sub LogToTextFile(ByVal LogName As String, ByVal newMessage As String)
Dim w As StreamWriter = File.AppendText(LogName)
LogIt(newMessage, w)
w.Close()
End Sub
Public Shared Sub LogIt(ByVal logMessage As String, ByVal wr As StreamWriter)
wr.Write(ControlChars.CrLf & "Log Entry:")
wr.WriteLine("(0) {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
wr.WriteLine(" :")
wr.WriteLine(" :{0}", logMessage)
wr.WriteLine("---------------------------")
wr.Flush()
End Sub
Public Shared Sub LotToEventLog(ByVal errorMessage As String)
Dim log As System.Diagnostics.EventLog = New System.Diagnostics.EventLog
log.Source = "My Application"
log.WriteEntry(errorMessage)
End Sub
End Class
2) Make & register its assembly, in SQL Server 2005.
3)Create Stored Procedure as given below:
CREATE PROCEDURE dbo.SP_LogTextFile
(
@LogName nvarchar(255), @NewMessage nvarchar(255)
)
AS EXTERNAL NAME
[asmLog].[WriteLog.WLog].[LogToTextFile]
4) When i execute this stored procedure as
Execute SP_LogTextFile 'C:Test.txt','Message1'
5) Then i got the following error
Msg 6522, Level 16, State 1, Procedure SP_LogTextFile, Line 0
A .NET Framework error occurred during execution of user defined routine or aggregate 'SP_LogTextFile':
System.UnauthorizedAccessException: Access to the path 'C:Test.txt' is denied.
System.UnauthorizedAccessException:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, ileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
at System.IO.File.AppendText(String path)
at WriteLog.WLog.LogToTextFile(String LogName, String newMessage)
View 13 Replies
View Related
Nov 8, 2006
G'day everyoneThat's a space between the ticks.It's all part of a longer script but seeing as the failure occurs online 1if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[config]') and OBJECTPROPERTY(id, N'IsUserTable') =1)drop table [dbo].[config]GOThat's three lines only. Does it matter that they're in Unicode?Any ideas?Kind regards,Bruce M. AxtensSoftware EngineerStrapper Technologies
View 3 Replies
View Related
Jul 6, 2006
I am trying to use the Bulk Insert Task to load from a csv file. My final column is a bit that is nullable. My file is an ID column that is int, a date column that is mm/dd/yyy, then 20 columns that are real, and a final column that is bit. I've tried various combinations of codepage and datafiletype on my task component. When I have RAW with Char, I get the error included below. If I change to RAW/Native or codepage 1252, I don't have an issue with the bit; however, errors start generating on the ID and date columns.
I have tried various data type settings on my flat file connection, too. I have tried DT_BOOL and the integer datatypes. Nothing seems to work.
I hope someone can help me work through this.
Thanks in advance,
SK
SSIS package "Package3.dtsx" starting.
Error: 0xC002F304 at Bulk Insert Task, Bulk Insert Task: An error occurred with the following error message: "Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.The bulk load failed. The column is too long in the data file for row 1, column 24. Verify that the field terminator and row terminator are specified correctly.Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 23 (cancelled).".
Error: 0xC002F304 at Bulk Insert Task 1, Bulk Insert Task: An error occurred with the following error message: "Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.The bulk load failed. The column is too long in the data file for row 1, column 24. Verify that the field terminator and row terminator are specified correctly.Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 23 (cancelled).".
Task failed: Bulk Insert Task 1
Task failed: Bulk Insert Task
Warning: 0x80019002 at Package3: The Execution method succeeded, but the number of errors raised (2) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "Package3.dtsx" finished: Failure.
View 5 Replies
View Related
Jun 30, 2007
Hi all,
I am developing ASP.NET 1.1 application using VB.NET & SQL Server, on my machine I am using SQL Server 2000, and everything is working just fine.
The problem appears when I uploaded the site to the Host, they are using SQL Server 2005, is there any reason for this, I am using casting in the code, and I am sure there is something wrong with the hosting settings.
Any suggestions.
Best Regards
Wafi Mohtaseb
View 4 Replies
View Related
Mar 7, 2008
Hello Friends
How are you?? Friends i am getting problem in SQL Server 2005. I am deployng web application on production server as well as Databse also. In production server i inserted new field in all tables which is rowguid and its type is uniqueidentifier. The default binding for this field is newsequentialid(). In some pages it works ok but in some places it generates error like 'Conversion from type 'DBNull' to type 'String' is not valid'. Can anybody help me to solve this problem. Its urgent so plz reply me as soon as possible. I'll be very thankfull to you. Thanks in Advance.
Regards,
View 1 Replies
View Related
Nov 27, 2007
hi i dont know how to do type casting.
this.Variables.ObjVariable this objVariables i have create in variable place below like this
Name:Variable datatype int32 values 0
Name: NumberofRowsdatatype int32 values 10000
Name: ObjVariable datatype Object
My code
public override void CreateNewOutputRows()
{
/*
Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
*/
System.Data.OleDb.OleDbDataAdapter oLead = new System.Data.OleDb.OleDbDataAdapter();
//System.Data.Odbc.OdbcDataAdapter oLead = new System.Data.Odbc.OdbcDataAdapter();
//SqlDataAdapter oLead = new SqlDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
DataSet ds = (DataSet)this.Variables.ObjVariable; // here i am getting error
ds.Tables.Add(dt);
ADODB.Record rs = new ADODB.Record();
oLead.Fill(ds, rs, "Variables");
foreach (DataRow row in dt.Rows)
{
{
Output0Buffer.AddRow();
Output0Buffer.Column = (int)row["Column"];
Output0Buffer.Column1 = row["Column1"].ToString();
Output0Buffer.Column2 = row["Column2"].ToString();
}
}
}
}
This is the error
Unable to cast object of type 'System.Object' to type 'System.Data.DataSet'.
at ScriptMain.CreateNewOutputRows()
at UserComponent.PrimeOutput(Int32 Outputs, Int32[] OutputIDs, PipelineBuffer[] Buffers)
at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PrimeOutput(Int32 outputs, Int32[] outputIDs, PipelineBuffer[] buffers)
thanks
kedaranth
View 5 Replies
View Related
Feb 1, 2006
Hi,I am getting the following error from the query below against SQLServer 8.00.2039 (SP4)Error:====Server: Msg 107, Level 16, State 2, Line 1The column prefix 'd' does not match with a table name or alias nameused in the query.Select Statement:=============select ....from trades a,gems_product_groups b,portfolio_nav_mapping c,products d,limit_types eleft outer join gems_prod_trade_mod f on d.product_id =f.product_IDI know this was a known bug in MS-SQL7, but I thought it had been fixedin 2000.Can anyone help?Thanks
View 3 Replies
View Related
Jun 7, 2005
Simple SQL Error Can anyone help for a new starter. Error MessageServer: Msg 209, Level 16, State 1, Line 6 Ambiguous column name 'CustomerID'.Codeselect CustomerID, ContactName, OrderId from CustomersInner Join Orders OnCustomers.CustomerID = Orders.CustomerIDDBMS = SQL Server 2000 SP 3aDatabase = NorthwindI have no idea why i receive this error
View 1 Replies
View Related
Mar 16, 2001
Hi, I would appreciate your help. I donot know why I am getting this error when I run this query :
if (select SUBSTRING(de_ftpdownload,1,CHARINDEX('.',de_ftpdow nload,0)-1)as de_ftpdownload from vendor_invoice)
<> (select stamp_number from vendor_invoice)
select 'no'
else
select 'yes'
I get this Error
Server: Msg 536, Level 16, State 3, Line 1
Invalid length parameter passed to the substring function.
----
yes
(1 row(s) affected)
I would appreciate your hlep
Al
View 1 Replies
View Related
Jun 23, 2004
Can anybody help me with this syntax?
select
PHN.N_PHN_ID 'ID',
PHN.N_PHN_AREACD 'AREAD1',
PHN.N_PHN_PREFIX 'PREFIXD1',
PHN.N_PHN_NUMBER 'NBRD1',
PHN.N_PHN_EXTENTN 'EXTD1',
PHN2.N_PHN_AREACD 'AREAD2',
PHN2.N_PHN_PREFIX 'PREFIXD2',
PHN2.N_PHN_NUMBER 'NBRD2',
PHN2.N_PHN_EXTENTN 'EXTD2'
from Donor_Visit2 DV2 RIGHT OUTER JOIN NAT_PHN_DB_REC PHN
ON DV2.COUNT_INSTID = PHN.N_PHN_INSTID
RIGHT OUTER JOIN NAT_PHN_DB_REC PHN2
ON DV2.COUNT_ID = PHN2.PHN.N_PHN_ID
order by PHN.N_PHN_ID
here is the error message:
Server: Msg 107, Level 16, State 2, Line 1
The column prefix 'PHN2.PHN' does not match with a table name or alias name used in the query.
View 1 Replies
View Related
Nov 22, 2004
Hello All,
This table was created by coldfusion and has been given all priviliges to public and I am in the public group but I still cant select from it. It gives me this error message: Server: Msg 208, Level 16, State 1, Line 1. Help!
Thanks in Advance.
View 5 Replies
View Related
Feb 15, 2008
I'm getting this error in SQL server.
Msg 8101, Level 16, State 1, Line 68
An explicit value for the identity column in table 'temp_notes' can only be specified when a column list is used and IDENTITY_INSERT is ON.
My original script looked like this.
SET NOCOUNT ON
DECLARE @patient_id int
,@phn varchar(9)
,@full_name varchar(100)
,@birth_date datetime
,@entry_note varchar(8000)
,@entry_date datetime
,@rec_counter int
,@Clinic_identifier varchar(24)
,@chart_count int
set @Clinic_identifier = 'MEDOWL.'
set @rec_counter = 0
DECLARE patients_cursor CURSOR FOR
SELECT a.full_name, a.birth_date, a.phn, a.patient_id
FROM patient as a
,clinicdoctors as b
WHERE a.patient_id IN (51450,49741,57290) --= 51450
and datalength(a.phn) = 9
and b.clinicdoctor_id = a.clinicdoctor_id
ORDER BY a.last_name,a.first_name,a.patient_id
OPEN patients_cursor
FETCH NEXT FROM patients_cursor
INTO @full_name, @birth_date, @phn, @patient_id
--select @full_name, @birth_date, @phn, @patient_id
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE chartcount_cursor CURSOR FOR
select count(*)
from ChartEntries
where patient_id = @patient_id
OPEN chartcount_cursor
FETCH NEXT FROM chartcount_cursor INTO @chart_count
--select @chart_count as chtcount
DECLARE chartentries_cursor CURSOR FOR
select entry_datetime,entry_note
from ChartEntries
where patient_id = @patient_id
order by Patient_id, ChartEntry_Id desc
-- Variable value from the outer cursor
OPEN chartentries_cursor
FETCH NEXT FROM chartentries_cursor INTO @entry_date,@entry_note
--select @entry_date,@entry_note
WHILE @@FETCH_STATUS = 0
BEGIN
set @rec_counter = @rec_counter + 1
--select @@FETCH_STATUS as status
IF @@FETCH_STATUS = 0
insert into temp_notes
values (@Clinic_identifier+@phn+'.'
+convert(varchar,@rec_counter)+'.'
+convert(varchar,@chart_count),
@phn,
@full_name,
@birth_date,
@entry_date,
@entry_note
)
-- Get the next entry note
FETCH NEXT FROM chartentries_cursor INTO @entry_date,@entry_note
--select @entry_date,@entry_note
END
CLOSE chartentries_cursor
DEALLOCATE chartentries_cursor
CLOSE chartcount_cursor
DEALLOCATE chartcount_cursor
set @rec_counter = 0
set @chart_count = 0
-- Get the next patient record
FETCH NEXT FROM patients_cursor
INTO @full_name, @birth_date, @phn, @patient_id
--select @full_name, @birth_date, @phn, @patient_id
-- Get the next chart record count
--FETCH NEXT FROM chartcount_cursor INTO @chart_count
--select @chart_count as chtcount
END
CLOSE patients_cursor
DEALLOCATE patients_cursor
GO
I then changed it to left pad the variables @rec_counter and @chart_count.
SET NOCOUNT ON
DECLARE @patient_id int
,@phn varchar(9)
,@full_name varchar(100)
,@birth_date datetime
,@entry_note varchar(8000)
,@entry_date datetime
,@rec_counter int
,@Clinic_identifier varchar(24)
,@chart_count int
set @Clinic_identifier = 'MEDOWL.'
set @rec_counter = 0
DECLARE patients_cursor CURSOR FOR
SELECT a.full_name, a.birth_date, a.phn, a.patient_id
FROM patient as a
,clinicdoctors as b
WHERE a.patient_id IN (51450,49741,57290) --= 51450
and datalength(a.phn) = 9
and b.clinicdoctor_id = a.clinicdoctor_id
ORDER BY a.last_name,a.first_name,a.patient_id
OPEN patients_cursor
FETCH NEXT FROM patients_cursor
INTO @full_name, @birth_date, @phn, @patient_id
--select @full_name, @birth_date, @phn, @patient_id
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE chartcount_cursor CURSOR FOR
select count(*)
from ChartEntries
where patient_id = @patient_id
OPEN chartcount_cursor
FETCH NEXT FROM chartcount_cursor INTO @chart_count
--select @chart_count as chtcount
DECLARE chartentries_cursor CURSOR FOR
select entry_datetime,entry_note
from ChartEntries
where patient_id = @patient_id
order by Patient_id, ChartEntry_Id desc
-- Variable value from the outer cursor
OPEN chartentries_cursor
FETCH NEXT FROM chartentries_cursor INTO @entry_date,@entry_note
--select @entry_date,@entry_note
WHILE @@FETCH_STATUS = 0
BEGIN
set @rec_counter = @rec_counter + 1
--select @@FETCH_STATUS as status
IF @@FETCH_STATUS = 0
insert into temp_notes
values (@Clinic_identifier+@phn+'.'
+REPLICATE('0',3),convert(varchar,@rec_counter)+'. '
+REPLICATE('0',3),convert(varchar,@chart_count),
@phn,
@full_name,
@birth_date,
@entry_date,
@entry_note
)
-- Get the next entry note
FETCH NEXT FROM chartentries_cursor INTO @entry_date,@entry_note
--select @entry_date,@entry_note
END
CLOSE chartentries_cursor
DEALLOCATE chartentries_cursor
CLOSE chartcount_cursor
DEALLOCATE chartcount_cursor
set @rec_counter = 0
set @chart_count = 0
-- Get the next patient record
FETCH NEXT FROM patients_cursor
INTO @full_name, @birth_date, @phn, @patient_id
--select @full_name, @birth_date, @phn, @patient_id
-- Get the next chart record count
--FETCH NEXT FROM chartcount_cursor INTO @chart_count
--select @chart_count as chtcount
END
CLOSE patients_cursor
DEALLOCATE patients_cursor
GO
That is when I received the error, so I inserted this command before the insert line but it made no difference.
SET IDENTITY_INSERT temp_notes ON
insert into temp_notes
values (@Clinic_identifier+@phn+'.'
+REPLICATE('0',3),convert(varchar,@rec_counter)+'. '
+REPLICATE('0',3),convert(varchar,@chart_count),
@phn,
@full_name,
@birth_date,
@entry_date,
@entry_note
)
I'm concatenating four different variables together to insert into the column note_id.
What is the problem? I just don't see it. My table definition looks like this.
CREATE TABLE [dbo].[temp_notes](
[temp_Id] [int] IDENTITY(1,1) NOT NULL,
[note_Id] [varchar](24) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[phn] [char](9) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[full_name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[birth_date] [datetime] NULL,
[entry_datetime] [datetime] NULL,
[Entry_Note] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_temp_notes] PRIMARY KEY CLUSTERED
(
[temp_Id] ASC
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
View 2 Replies
View Related
Dec 4, 2007
Error 4305
What would be the cause of this error?
Msg 4305, Level 16, State 1, Line 1
The log in this backup set begins at LSN 8229000000047200001, which is too recent to apply to the database. An earlier log backup that includes LSN 8219000000021400001 can be restored
And what would the fix be?
I am trying to restore from a Full Backup and then the log files on a development machine.
Cheers,
Casey
View 5 Replies
View Related
Aug 2, 2007
Hi,
I have built a stored procedure and the code is like below:
Code Snippet
DECLARE @Table_Name VARCHAR(100)
DECLARE @Table_Desc SQL_VARIANT
DECLARE @Query VARCHAR(8000)
USE HRD
SELECT @Table_Name = 'Employee'
SELECT @Query = 'IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[DEL_' + UPPER(@Table_Name) + ']''))
DROP TRIGGER [dbo].[DEL_' + UPPER(@Table_Name) + ']'
EXEC(@Query)
SELECT @Table_Desc = (SELECT a.value
FROM
sys.extended_properties a, sys.tables b
WHERE a.major_id = b.object_id
AND a.minor_id = 0
AND a.name = 'MS_DESCRIPTION'
AND b.name = @Table_Name)
SELECT @Query = '''CREATE TRIGGER [DEL_' + UPPER(@Table_Name) + '] ON dbo.' + @Table_Name + '
FOR DELETE
AS
DECLARE @Old_Value VARCHAR(8000)
DECLARE @New_Value VARCHAR(8000)
DECLARE @P_Key VARCHAR(8000)
DECLARE @P_Key_Value VARCHAR(8000)
DECLARE @P_Key_Insert VARCHAR(8000)
DECLARE @Comment VARCHAR(8000)
SELECT @P_Key_Insert = ''''''''
EXEC(''''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''''''''[dbo].[Temp_PrimKey]'''''''') AND type in (N''''''''U''''''''))
DROP TABLE [dbo].[Temp_PrimKey]'''')
SELECT K.COLUMN_NAME INTO Temp_PrimKey
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
ON T.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE
T.CONSTRAINT_TYPE = ''''PRIMARY KEY'''' AND T.TABLE_NAME = ''''' + @Table_Name + '''''
EXEC(''''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''''''''[dbo].[Temp_Value]'''''''') AND type in (N''''''''U''''''''))
DROP TABLE [dbo].[Temp_Value]'''')
EXEC(''''CREATE TABLE [dbo].[Temp_Value](
[PValue] [VARCHAR](max) NOT NULL
) ON [PRIMARY]'''')
EXEC(''''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''''''''[dbo].[Temp_Deleted]'''''''') AND type in (N''''''''U''''''''))
DROP TABLE [dbo].[Temp_Deleted]'''')
SELECT * INTO Temp_Deleted FROM deleted
DECLARE Curs_PrimKey CURSOR FOR
SELECT * FROM Temp_PrimKey
OPEN Curs_PrimKey
FETCH NEXT FROM Curs_PrimKey INTO @P_Key
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC(''''INSERT INTO Temp_Value SELECT ''''+ @P_Key + '''' FROM Temp_Deleted'''')
SELECT @P_Key_Value = (SELECT PValue FROM Temp_Value)
EXEC(''''DELETE FROM Temp_Value'''')
SELECT @P_Key_Insert = @P_Key_Insert + @P_Key + '''' = '''' + @P_Key_Value + '''', ''''
FETCH NEXT FROM Curs_PrimKey INTO @P_Key
END
CLOSE Curs_PrimKey
DEALLOCATE Curs_PrimKey
EXEC(''''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''''''''[dbo].[Temp_Deleted]'''''''') AND type in (N''''''''U''''''''))
DROP TABLE [dbo].[Temp_Deleted]'''')
EXEC(''''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''''''''[dbo].[Temp_Value]'''''''') AND type in (N''''''''U''''''''))
DROP TABLE [dbo].[Temp_Value]'''')
SELECT @P_Key_Insert = LEFT(@P_Key_Insert, LEN(@P_Key_Insert)-2)
SELECT @Comment = ''''' + CAST(@Table_Desc AS VARCHAR) + ' deleted, '''' + @P_Key_Insert
INSERT INTO TLOG(Log_Date, Log_Reference, Log_Comment)
VALUES (GETDATE(), @P_Key_Insert, @Comment)
'''
--PRINT @Query
EXEC(@Query)
Problem is when I run it gives error:
Msg 102, Level 15, State 1, Line 1Incorrect syntax near 'CREATE TRIGGER [DEL_EMPLOYEE] ON dbo.Employee FOR DELETEAS DECLARE @Old_Value VARCHAR(8000)DECLARE @New_Value VARCHA'.
If I print the @Query and run it in a query analyzer using the statement EXEC it worked. It's giving me headache, this supposed to be a simple exec statement. Please advise. Thanks.
View 2 Replies
View Related
Jul 19, 2006
Hello Folks,
I am moving the model & Msdb databases to a different location and I have this error.
Thanks
Msg 3710, Level 16, State 1, Line 1
Cannot detach an opened database when the server is in minimally configured mode.
View 3 Replies
View Related
Jul 23, 2005
Hi all,I have a table called PTRANS with few columns (see create script below).I have created a view on top that this table VwTransaction (See below)I can now run this query without a problem:select * from dbo.VwTransactionwhereAssetNumber = '101001' andTransactionDate <= '7/1/2003'But when I create an index on the PTRANS table using the command below:CREATE INDEX IDX_PTRANS_CHL# ON PTRANS(CHL#)The same query that ran fine before, fails with the error:Server: Msg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted inan out-of-range datetime value.I can run the same query by commeting out the AssetNumber clause and itworks fine. I can also run the query commenting out the TransactionDatecolumn and it works fine. But when I have both the conditions in theWHERE clause, it gives me this error. Dropping the index solves theproblem.Can anyone tell me why an index would cause a query to fail?Thanks a lot in advance,AmirCREATE TABLE [PTRANS] ([CHL#] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[CHCENT] [numeric](2, 0) NOT NULL ,[CHYYMM] [numeric](4, 0) NOT NULL ,[CHDAY] [numeric](2, 0) NOT NULL ,[CHTC] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ON [PRIMARY]GOCREATE VIEW dbo.vwTransactionsASSELECT CONVERT(datetime, dbo.udf_AddDashes(REPLICATE('0', 2 -LEN(CHCENT)) + CONVERT(varchar, CHCENT) + REPLICATE('0', 4 -LEN(CHYYMM))+ CONVERT(varchar, CHYYMM) + REPLICATE('0', 2 -LEN(CHDAY)) + CONVERT(varchar, CHDAY)), 20) AS TransactionDate,CHL# AS AssetNumber,CHTC AS TransactionCodeFROM dbo.PTRANSWHERE (CHCENT <> 0) AND (CHTC <> 'RA')*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View 1 Replies
View Related
Jan 25, 2002
If we run the query below with the values of 'rml' and 'ra' it runs but if we use 'cca' and 'cc' we get this error:
Server: Msg 1101, Level 17, State 10, Line 8
Could not allocate new page for database 'TEMPDB'. There are no more pages available in filegroup DEFAULT. Space can be created by dropping objects, adding additional files, or allowing file growth.
Here is the query
Declare @Level_1 varchar(3),
@Level_2 varchar(2)
Select @Level_1 = 'cca'
Select @Level_2 = 'cc'
select distinct tblAsset.State, tblAsset.County, tblAsset.Plant, tblAsset.Account,
tblAsset.Acq_Yr, tblAsset.Acq_Pd, tblAsset_Book.Cost_Original,
tblCounty_Names.County_Name, CER..tblLocation.Location,
tblGL_Account.Account_Desc
from tblAsset, tblAsset_Book, tblCounty_Names, CER..tblLocation, tblGL_Account
where tblAsset_Book.Level_1 = @Level_1
and tblAsset.Level_1 = tblAsset_Book.Level_1
and tblAsset_Book.Level_2 = @Level_2
and tblAsset.Level_2 = tblAsset_Book.Level_2
and tblGL_Account.Company = tblAsset.Level_2
and CER..tblLocation.SBU = tblGL_Account.Company
and tblCounty_Names.County = tblAsset.County
and CER..tblLocation.County = tblCounty_Names.County
and CER..tblLocation.Code = tblAsset.Plant
and tblGL_Account.Account = tblAsset.Account
and tblAsset_Book.Book_Number = '1'
order by tblAsset.State
View 1 Replies
View Related
Jan 5, 2001
When I try to update one table from another I get the following error
message, Does anyone know what may be the cause of the error :
Server: Msg 8152, Level 16, State 9, Line 1
String or binary data would be truncated.
The statement has been terminated.
Thanks
KUL
View 2 Replies
View Related
Feb 9, 2006
Dear All participants.
My distribution log file size is reached upto 33GB, What I should do?
Any clue or helps are too appreciable.
Thanks
R.Mall
View 3 Replies
View Related
Aug 25, 2007
i have sp4 install. Anyone know how to fix it?
Server: Msg 2537, Level 16, State 43, Line 1
Table error: Object ID 1376776012, index ID 0, page (1:56868), row 2. Record check (Valid SqlVariant) failed. Values are 7 and 0.
Server: Msg 2537, Level 16, State 1, Line 1 ... so on
=============================
http://www.sqlserverstudy.com
View 9 Replies
View Related
Nov 23, 2005
Dear (and mighty) all:I backed up a database (SQL server 7.0) and tried to restore it onanother system (SQL Server 2000). This is not the first time I'm doingthis and never had a problem before:-- in the source dbBACKUP db_icoaraci TO DISK = 'C:TEMPBACKUP-ICOARACI.DAT'--in the destination dbRESTORE db_icoaraci FROM DISK='E:TEMPBACKUP-ICOARACI.DAT'WITH MOVE='ICOARACI_DAT' TO 'E:DBICOARACI.MDF',MOVE='ICOARACI_LOG' TO 'E:DBICOARACI.LDF'Today, to my surprise, the destination SQL returned the followingerror:Processed 25592 pages for database 'db_icoaraci', file 'ICOARACI_DAT'on file 1.Processed 1 pages for database 'db_icoaraci', file 'ICOARACI_LOG' onfile 1.Server: Msg 1105, Level 17, State 2, Line 1Could not allocate space for object '(SYSTEM table id: 6)' in database'db_icoaraci' because the 'PRIMARY' filegroup is full.Server: Msg 3013, Level 16, State 1, Line 1RESTORE DATABASE is terminating abnormally.I searched the list and a found a few posts refering to the same error,but none in the exactly same scenario.I tried to restore the database with NORECOVERY, and, before restoringthe log, increase its size (ALTER DATABASE ... etc), but SQL Serversays that the DB couldn't be open because it's in the middle of arestore...I'll appreciate any help.Regards,Branco.
View 3 Replies
View Related
Dec 17, 2007
I am experiencing some frustration in regards to parsing an email that I need to work with.
(I don't have control over the format of the email I am receiving)
Any help would be appreciated.
Thank you
Jake
Here is the error I get, when I use the SQL Query Analyzer to process my Stored Procedure. (Not every email gets this error, just some, others process just fine.)
String or binary data would be truncated.
The statement has been terminated.
Stored Procedure: eResponse.dbo.spParser
Return Code = -6
My Code is as follows:
CREATE PROCEDURE spParser
@_id nvarchar(50)
AS
--assumes the email is no longer than 4000 characters. if it might be longer, bump this number up.
-- Common Varriables
DECLARE @body nvarchar(4000)
DECLARE @i int
DECLARE @phone nvarchar(50)
DECLARE @phonestart int
DECLARE @phoneend int
DECLARE @email nvarchar(50)
DECLARE @emailstart int
DECLARE @emailend int
DECLARE @comments nvarchar(3000)
DECLARE @commentsstart int
DECLARE @commentsend int
DECLARE @OrigID varchar(50)
-- Jose Ole Variables
DECLARE @firstname nvarchar(50)
DECLARE @firstnamestart int
DECLARE @firstnameend int
DECLARE @lastname nvarchar(50)
DECLARE @lastnamestart int
DECLARE @lastnameend int
DECLARE @address1 nvarchar(50)
DECLARE @address1start int
DECLARE @address1end int
DECLARE @address2 nvarchar(50)
DECLARE @address2start int
DECLARE @address2end int
DECLARE @city nvarchar(50)
DECLARE @citystart int
DECLARE @cityend int
DECLARE @state nvarchar(5)
DECLARE @statestart int
DECLARE @stateend int
DECLARE @zip nvarchar(15)
DECLARE @zipstart int
DECLARE @zipend int
DECLARE @country nvarchar(50)
DECLARE @countrystart int
DECLARE @countryend int
DECLARE @phone2 nvarchar(50)
DECLARE @phone2start int
DECLARE @phone2end int
DECLARE @productname nvarchar(50)
DECLARE @productnamestart int
DECLARE @productnameend int
DECLARE @upccode nvarchar(50)
DECLARE @upccodestart int
DECLARE @upccodeend int
DECLARE @datecode nvarchar(50)
DECLARE @datecodestart int
DECLARE @datecodeend int
DECLARE @purchaseat nvarchar(50)
DECLARE @purchaseatstart int
DECLARE @purchaseatend int
DECLARE @purchasecity nvarchar(50)
DECLARE @purchasecitystart int
DECLARE @purchasecityend int
DECLARE @datepurchased nvarchar(50)
DECLARE @datepurchasedstart int
DECLARE @datepurchasedend int
DECLARE @dateopened nvarchar(50)
DECLARE @dateopenedstart int
DECLARE @dateopenedend int
DECLARE @subject nvarchar(50)
DECLARE @subjectstart int
DECLARE @subjectend int
-- Windosr Variables
DECLARE @name nvarchar(50)
DECLARE @namestart int
DECLARE @nameend int
DECLARE @company nvarchar(50)
DECLARE @companystart int
DECLARE @companyend int
--First replace all ASCII carriage returns and line feeds and assign the whole chunk of data to a variable.
SET @body = (select replace( REPLACE(convert(varchar(4000), message),CHAR(10),' '),CHAR(13),'') from message where mailid = @_id)
--below is the sample syntax for the individual replacements of line feeds and carriage returns, but it's combined into one statement above.
--SELECT REPLACE(@jb,CHAR(10),'') as firstpass
--SELECT REPLACE(@jb,CHAR(13),'') as secondpass
IF left(@body,47) = 'Fromubject:contact info sent from samplesite.com'
--If this is true.. then it is a sample company.
BEGIN
--The 12 in the start is compensating for the 12 Characters of "First Name: "
--Below is collecting First Name
SET @firstnamestart = (CHARINDEX('First name:',@body) + 11)
SET @firstnameend = (CHARINDEX('Last name:',@body) - 1)
SET @firstname = SUBSTRING(@body,@firstnamestart,@firstnameend-@firstnamestart)
----Below is collecting Last Name
SET @lastnamestart = (CHARINDEX('Last name:',@body) + 10)
SET @lastnameend = (CHARINDEX('Address 1:',@body) - 1)
SET @lastname = SUBSTRING(@body,@lastnamestart,@lastnameend-@lastnamestart)
--Below is collecting Address1
SET @address1start = (CHARINDEX('Address 1:',@body) + 10)
SET @address1end = (CHARINDEX('Address 2:',@body) - 1)
SET @address1 = SUBSTRING(@body,@address1start,@address1end-@address1start)
--Below is collecting Address2
SET @address2start = (CHARINDEX('Address 2:',@body) + 10)
SET @address2end = (CHARINDEX('City:',@body) - 1)
SET @address2 = SUBSTRING(@body,@address2start,@address2end-@address2start)
--Below is collecting city information
SET @citystart = (CHARINDEX('City:',@body) + 5)
SET @cityend = (CHARINDEX('State/Prov',@body) -1)
SET @city = SUBSTRING(@body,@citystart,@cityend-@citystart)
--Below is collecting state information
SET @statestart = (CHARINDEX('State/Province:',@body) + 15)
SET @stateend = (CHARINDEX('Zip/Postal',@body) -1)
SET @state = SUBSTRING(@body,@statestart,@stateend-@statestart)
--Below is collecting zip information
SET @zipstart = (CHARINDEX('Zip/Postal Code:',@body) + 16)
SET @zipend = (CHARINDEX('Country',@body) -1)
SET @zip = SUBSTRING(@body,@zipstart,@zipend-@zipstart)
--Below is collecting country information
SET @countrystart = (CHARINDEX('Country:',@body) + 8)
SET @countryend = (CHARINDEX('E-mail address',@body) -1)
SET @country = SUBSTRING(@body,@countrystart,@countryend-@countrystart)
--Below is collecting email information
SET @emailstart = (CHARINDEX('E-mail address:',@body) + 15)
SET @emailend = (CHARINDEX('Daytime',@body) -1)
SET @email = SUBSTRING(@body,@emailstart,@emailend-@emailstart)
--Below is collecting phone information
SET @phonestart = (CHARINDEX('Daytime Phone:',@body) + 14)
SET @phoneend = (CHARINDEX('Evening Phone:',@body) -1)
SET @phone = SUBSTRING(@body,@phonestart,@phoneend-@phonestart)
--Below is collecting phone2 information
SET @phone2start = (CHARINDEX('Evening Phone:',@body) + 14)
SET @phone2end = (CHARINDEX('Product Name',@body) -1)
SET @phone2 = SUBSTRING(@body,@phone2start,@phone2end-@phone2start)
--Below is collecting Product Name information
SET @productnamestart = (CHARINDEX('Product Name:',@body) + 12)
SET @productnameend = (CHARINDEX('UPC Code:',@body) -1)
SET @productname = SUBSTRING(@body,@productnamestart,@productnameend-@productnamestart)
--Below is collecting UPC Code information
SET @upccodestart = (CHARINDEX('UPC Code:',@body) + 9)
SET @upccodeend = (CHARINDEX('Date Code:',@body) -1)
SET @upccode = SUBSTRING(@body,@upccodestart,@upccodeend-@upccodestart)
--Below is collecting Date Code information
SET @datecodestart = (CHARINDEX('Date Code:',@body) + 10)
SET @datecodeend = (CHARINDEX('Purchased At',@body) -1)
SET @datecode = SUBSTRING(@body,@datecodestart,@datecodeend-@datecodestart)
--Below is collecting Purchase At information
SET @purchaseatstart = (CHARINDEX('Purchased At',@body) + 26)
SET @purchaseatend = (CHARINDEX('Purchase City:',@body) -1)
SET @purchaseat = SUBSTRING(@body,@purchaseatstart,@purchaseatend-@purchaseatstart)
--Below is collecting Purchase City information
SET @purchasecitystart = (CHARINDEX('Purchase City:',@body) + 14)
SET @purchasecityend = (CHARINDEX('Date Purchased',@body) -1)
SET @purchasecity = SUBSTRING(@body,@purchasecitystart,@purchasecityend-@purchasecitystart)
--Below is collecting Date Purchased information
SET @datepurchasedstart = (CHARINDEX('Date Purchased:',@body) + 15)
SET @datepurchasedend = (CHARINDEX('Date Opened',@body) -1)
SET @datepurchased = SUBSTRING(@body,@datepurchasedstart,@datepurchasedend-@datepurchasedstart)
--Below is collecting Date Opened information
SET @dateopenedstart = (CHARINDEX('Date Opened:',@body) + 12)
SET @dateopenedend = (CHARINDEX('E-mail Subject:',@body) -1)
SET @dateopened = SUBSTRING(@body,@dateopenedstart,@dateopenedend-@dateopenedstart)
--Below is collecting Email Subject information
SET @subjectstart = (CHARINDEX('E-mail Subject:',@body) + 15)
SET @subjectend = (CHARINDEX('Comments:',@body) -1)
SET @subject = SUBSTRING(@body,@subjectstart,@subjectend-@subjectstart)
--Below is collecting message information
SET @commentsstart = (CHARINDEX('Comments:',@body) + 10)
SET @commentsend = len(@body)
SET @comments = SUBSTRING(@body,@commentsstart,@commentsend-@commentsstart)
--below is the part that actually writes the data out to the Output table
INSERT INTO OutputEmails
(FirstName, LastName, Address1, Address2, City, State, Zip, Country, eMail, Phone, Phone2, ProductName, UPCCode, DateCode, PurchaseAt, PurchaseCity, DatePurchased, DateOpened, Subject, Comments, OrigID)
SELECT
ltrim(SUBSTRING(@body,@firstnamestart,@firstnameend-@firstnamestart)) as FirstName,
ltrim(SUBSTRING(@body,@lastnamestart,@lastnameend-@lastnamestart)) as LastName,
ltrim(SUBSTRING(@body,@address1start,@address1end-@address1start)) as Address1,
ltrim(SUBSTRING(@body,@address2start,@address2end-@address2start)) as Address2,
ltrim(SUBSTRING(@body,@citystart,@cityend-@citystart)) as City,
ltrim(SUBSTRING(@body,@statestart,@stateend-@statestart)) as State,
ltrim(SUBSTRING(@body,@zipstart,@zipend-@zipstart)) as Zip,
ltrim(SUBSTRING(@body,@countrystart,@countryend-@countrystart)) as Country,
ltrim(SUBSTRING(@body,@emailstart,@emailend-@emailstart)) as eMail,
ltrim(SUBSTRING(@body,@phonestart,@phoneend-@phonestart)) as Phone,
ltrim(SUBSTRING(@body,@phone2start,@phone2end-@phone2start)) as Phone2,
ltrim(SUBSTRING(@body,@productnamestart,@productnameend-@productnamestart)) as ProductName,
ltrim(SUBSTRING(@body,@upccodestart,@upccodeend-@upccodestart)) as UPCCode,
ltrim(SUBSTRING(@body,@datecodestart,@datecodeend-@datecodestart)) as DateCode,
ltrim(SUBSTRING(@body,@purchaseatstart,@purchaseatend-@purchaseatstart)) as PurchaseAt,
ltrim(SUBSTRING(@body,@purchasecitystart,@purchasecityend-@purchasecitystart)) as PurchaseCity,
ltrim(SUBSTRING(@body,@datepurchasedstart,@datepurchasedend-@datepurchasedstart)) as DatePurchased,
ltrim(SUBSTRING(@body,@dateopenedstart,@dateopenedend-@dateopenedstart)) as DateOpened,
ltrim(SUBSTRING(@body,@subjectstart,@subjectend-@subjectstart)) as Subject,
ltrim(SUBSTRING(@body,@commentsstart,@commentsend-@commentsstart)) as Comments,
@_id as OrigID
FROM dbo.message
WHERE (mailId = @_id)
END
ELSE BEGIN
--below prints the whole value in the debugger (SQL Query Analyzer)
--print @body
--below prints the length of the whole value
--print len(@body)
--below prints the location of 'Callers Name:'
--Print CHARINDEX('Name: ',@body)
--Below is collecting the Name information
--The 6 in the start is compensating for the 6 Characters of "Name: "
SET @namestart = (CHARINDEX('Name:',@body) + 5)
SET @nameend = (CHARINDEX('Email:',@body) - 1)
SET @name = SUBSTRING(@body,@namestart,@nameend-@namestart)
--Below is collecting email information
SET @emailstart = (CHARINDEX('Email:',@body) + 6)
SET @emailend = (CHARINDEX('Title:',@body) -1)
SET @email = SUBSTRING(@body,@emailstart,@emailend-@emailstart)
--Below is collecting Company information
SET @companystart = (CHARINDEX('Company:',@body) + 8)
SET @companyend = (CHARINDEX('Phone Number:',@body) -1)
SET @company = SUBSTRING(@body,@companystart,@companyend-@companystart)
--Below is collecting phone information
SET @phonestart = (CHARINDEX('Phone Number:',@body) + 13)
SET @phoneend = (CHARINDEX('Comments:',@body) -1)
SET @phone = SUBSTRING(@body,@phonestart,@phoneend-@phonestart)
--Below is collecting message information
SET @commentsstart = (CHARINDEX('Comments:',@body) + 9)
SET @commentsend = len(@body)
SET @comments = SUBSTRING(@body,@commentsstart,@commentsend-@commentsstart)
--below is the part that actually writes the data out to the Output table
INSERT INTO OutputEmails
(Name, eMail, Company, Phone, Comments, OrigID)
SELECT
ltrim(SUBSTRING(@body,@namestart,@nameend-@namestart)) as Name,
ltrim(SUBSTRING(@body,@emailstart,@emailend-@emailstart)) as eMail,
ltrim(SUBSTRING(@body,@companystart,@companyend-@companystart)) as Company,
ltrim(SUBSTRING(@body,@phonestart,@phoneend-@phonestart)) as Phone,
ltrim(SUBSTRING(@body,@commentsstart,@commentsend-@commentsstart)) as Comments,
@_id as OrigID
FROM dbo.message
WHERE (mailId = @_id)
END
--At the very end when you're satisfied that the data has been processed properly, delete the appropriate message record from the message table
DELETE FROM MESSAGE Where message.mailID = @_ID
GO
Sample Data that has problems
Fromubject:contact info sent from samplesite.comBody:First name: Sample
Last name: Name
Address 1: 123 Testing Road
Address 2: Don't filled
City: Park Forest
State/Province: FL
Zip/Postal Code: 12345-1234
Country: USA
E-mail address: validemail@email.com
Daytime Phone: 123-123-1234
Evening Phone: Don't filled
Product Name: Sample Product with Cheese
UPC Code: 12345-89521
Date Code: 1251237 D PST . 5290
Purchased At (Store Name): StoreName
Purchase City: Store City
Date Purchased: 12/8/2007
Date Opened: 12/14/2007
E-mail Subject: nail in product
Comments: when I purchased your product, there was something in it. Obviously I am not happy about this. Please contact me. Thank you John Q Public
View 6 Replies
View Related
Aug 7, 2007
Dear All, I always got this error in CLR TVF:
Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.InvalidOperationException: Invalid attempt to FieldCount when reader is closed.
System.InvalidOperationException:
at System.Data.SqlClient.SqlDataReaderSmi.get_FieldCount()
at System.Data.Common.DbEnumerator.BuildSchemaInfo()
at System.Data.Common.DbEnumerator.MoveNext()
Here is my code:
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.Collections;
public static class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = "rowfiller",DataAccess=DataAccessKind.Read,TableDefinition = "ActID int, ActName nvarchar(50), ActCreatorID int,ActDesp nvarchar(200),ActCreateDate datetime,ActModifyDate datetime, ActStartDate datetime, ActEndDate datetime, Status int, Cost int")]
public static IEnumerable Func_GetSchCatActivityIDTable(int CatActivityID)
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
string sqlstring = "select * from Activity where CatActivityID=@CatActivityID;";
connection.Open();
SqlCommand command = new SqlCommand(sqlstring, connection);
command.Parameters.AddWithValue("@CatActivityID", CatActivityID);
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft Performance","CA1811:AvoidUncalledPrivateCode")]
public static void rowfiller(Object obj,
out SqlInt32 ActID,
out SqlString ActName,
out SqlInt32 ActCreatorID,
out SqlString ActDesp,
out SqlDateTime ActCreateDate,
out SqlDateTime ActModifyDate,
out SqlDateTime ActStartDate,
out SqlDateTime ActEndDate,
out SqlInt32 Status,
out SqlInt32 Cost,
)
{
SqlDataRecord row = (SqlDataRecord)obj;
int column = 0;
ActID = (row.IsDBNull(column)) ? SqlInt32.Null : new SqlInt32(row.GetInt32(column)); column++;
ActName = (row.IsDBNull(column)) ? SqlString.Null : new SqlString(row.GetString(column)); column++;
ActCreatorID = (row.IsDBNull(column)) ? SqlInt32.Null : new SqlInt32(row.GetInt32(column)); column++;
ActDesp = (row.IsDBNull(column)) ? SqlString.Null : new SqlString(row.GetString(column)); column++;
ActCreateDate = (row.IsDBNull(column)) ? SqlDateTime.Null : new SqlDateTime(row.GetDateTime(column)); column++;
ActModifyDate = (row.IsDBNull(column)) ? SqlDateTime.Null : new SqlDateTime(row.GetDateTime(column)); column++;
ActStartDate = (row.IsDBNull(column)) ? SqlDateTime.Null : new SqlDateTime(row.GetDateTime(column)); column++;
ActEndDate = (row.IsDBNull(column)) ? SqlDateTime.Null : new SqlDateTime(row.GetDateTime(column)); column++;
Status = (row.IsDBNull(column)) ? SqlInt32.Null : new SqlInt32(row.GetInt32(column)); column++;
Cost = (row.IsDBNull(column)) ? SqlInt32.Null : new SqlInt32(row.GetInt32(column)); column++;
}
};
Can anyone tell me what I am doing wrong? Many thanks
.
View 8 Replies
View Related