1

Is there a way of connecting and inserting data to a local SQL Server table through a batch file.

The table looks like on the database , ID | compName | availDiskSpace

For example, this would hold the local computer name and available space on the machine.

@echo off 
set computerName = computer123 
set diskSpace = 2GB
sqlcmd -S server1\SQLExpress 

Is it possible to insert these variables to the SQL table with an INSERT, I know i can use SELECT to select data but cantfind anywhere that shows INSERT .....Thanks

1
  • Insert from what source? Commented Sep 19, 2017 at 17:32

1 Answer 1

1

Assign variables using the -v argument for sqlcmd. For instance:

sqlcmd -S "server1\SQLExpress" -v diskSpace = "2GB" -v computerName = "Computer123" -q "insert into myTable (diskSpace, computerName) select '$(diskSpace)', '$(computerName)'"

You declare variables using -v and you reference them using $(<VariableName)

More detail on SQLCMD here: https://learn.microsoft.com/en-us/sql/tools/sqlcmd-utility

I believe all that should be fine to put in a batch script, but I imagine you can also set batch variables (as you did) and assign those to be the values of the sqlcmd variables.

FWIW, this is probably considerably easier to do with SSMS and/or a stored procedure.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Xedni, this makes sense now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.