Solved

invoke-sqlcmd : Error converting data type varchar to numeric

Posted on 2014-11-12
6
318 Views
Last Modified: 2014-12-08
Hello,

I try to collect dbspace with ps script :

-The table ddl and the ps script are  :

CREATE TABLE [dbo].[DSpace](
	[SERVERNAME] [varchar](50) NULL,
	[DatabaseName] [varchar](128) NULL,
	[Log_filename] [varchar](128) NULL,
	[Log_filesize] [decimal](18, 2) NULL,
	[Used_space] [decimal](18, 2) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

    $SQLInstance = "SQLTEST"

    $srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $SQLInstance

    $DBStats = $srv.Databases
		

        foreach ($DB in $DBStats) {
		IF ( $DB.status -eq "Normal" ) {
		$DBName = $DB.Name
		$db.get_logfiles() | % { New-Object PsObject -Property @{
		'Log File' = $_.FileName
		'Size (MB)' = [math]::round($_.Size/1KB,2)
		'Used Space (MB)' = [math]::round($_.UsedSpace/1KB,2)
		} | tee -Variable vals | Format-Table -auto
		
		$val.{Log File} 
		$val.{Size (MB)} 
		$val.{Used Space (MB)} 
	
		}
        $InsertResults = @"
   
		INSERT INTO DSpace (SERVERNAME ,DatabaseName ,Log_filename ,Log_filesize ,Used_space)
		VALUES ('$SQLInstance', '$DBName', '$val.{Log File}', '$val.{Size (MB)}', '$val.{Used Space (MB)}')
		
		"@
		

        invoke-sqlcmd @params -Query $InsertResults

		}
	}

Open in new window

The error returned is :
invoke-sqlcmd : Error converting data type varchar to numeric.
At line:20 char:9
+         invoke-sqlcmd @params -Query $InsertResults
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

How can I resolve this problem ?

Thanks
0
Comment
Question by:bibi92
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 69

Expert Comment

by:Qlemo
ID: 40438309
Remove the single quotes inside the INSERT statement for all numeric values, and you need to make them a subexpression inside of double quotes.
But there is another issue - if $DB.status is not "Normal", you still try to insert values, which are not recent by then - the INSERT belongs into the IF block.
And there is a typo in the tee-object, so the wrong variable is filled.
CREATE TABLE [dbo].[DSpace](
	[SERVERNAME] [varchar](50) NULL,
	[DatabaseName] [varchar](128) NULL,
	[Log_filename] [varchar](128) NULL,
	[Log_filesize] [decimal](18, 2) NULL,
	[Used_space] [decimal](18, 2) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

$SQLInstance = "SQLTEST"

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $SQLInstance

$DBStats = $srv.Databases
		

foreach ($DB in $DBStats) {
  IF ( $DB.status -eq "Normal" ) {
    $DBName = $DB.Name
    $db.get_logfiles() | % { New-Object PsObject -Property @{
      'Log File' = $_.FileName
      'Size (MB)' = [math]::round($_.Size/1KB,2)
      'Used Space (MB)' = [math]::round($_.UsedSpace/1KB,2)
    } | tee -Variable val | Format-Table -auto

    $InsertResults = @"
      INSERT INTO DSpace (SERVERNAME    , DatabaseName, Log_filename ,Log_filesize ,Used_space)
                  VALUES ('$SQLInstance', '$DBName'   , '$($val.{Log File})', $($val.{Size (MB)}), $($val.{Used Space (MB)}))	
"@
    invoke-sqlcmd @params -Query $InsertResults
  }
}

Open in new window

0
 
LVL 19

Expert Comment

by:Raheman M. Abdul
ID: 40438311
In your code you wrote the following:
tee -Variable vals

Is that val instead?
0
 

Author Comment

by:bibi92
ID: 40439454
For qlemo, thanks :
invoke-sqlcmd : Incorrect syntax near ','.
At line:1 char:1
+ invoke-sqlcmd @params -Query $InsertResults
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
0
Free Webinar: AWS Backup & DR

Join our upcoming webinar with experts from AWS, CloudBerry Lab, and the Town of Edgartown IT to discuss best practices for simplifying online backup management and cutting costs.

 
LVL 69

Expert Comment

by:Qlemo
ID: 40439807
Can't find any issue. Please add this before or after line 34 for debugging:
Write-Host $InsertResults

Open in new window

0
 
LVL 69

Accepted Solution

by:
Qlemo earned 500 total points
ID: 40439886
There is a syntax error in my code - a closing curly bracket missing. But that should have errored out pre-execution anything ...
foreach ($DB in $DBStats) {
  IF ( $DB.status -eq "Normal" ) {
    $DBName = $DB.Name
    $db.get_logfiles() | % {
      New-Object PsObject -Property @{
        'Log File' = $_.FileName
        'Size (MB)' = [math]::round($_.Size/1KB,2)
        'Used Space (MB)' = [math]::round($_.UsedSpace/1KB,2)
      } | tee -Variable val | Format-Table -auto

      $InsertResults = @"
        INSERT INTO DSpace (SERVERNAME    , DatabaseName, Log_filename ,Log_filesize ,Used_space)
                    VALUES ('$SQLInstance', '$DBName'   , '$($val.{Log File})', $($val.{Size (MB)}), $($val.{Used Space (MB)}))	
"@
      
      invoke-sqlcmd @params -Query $InsertResults
    }
  }
}

Open in new window

I've left the Format-Table as-is but it isn't what I would use - it is called for each line individually, insteadl of all the results together. On the other hand, if I change that, you won't see any intermediate results unless script execution is completed.
0
 

Author Comment

by:bibi92
ID: 40460942
ok i will test tomorrow. Thanks
0

Featured Post

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question