> 데이터 베이스 > MySQL 튜토리얼 > PowerShell에서 SQL Server 쿼리를 어떻게 실행할 수 있나요?

PowerShell에서 SQL Server 쿼리를 어떻게 실행할 수 있나요?

Susan Sarandon
풀어 주다: 2025-01-06 01:06:41
원래의
756명이 탐색했습니다.

How Can I Run SQL Server Queries from PowerShell?

PowerShell에서 SQL Server 쿼리 실행

PowerShell은 로컬 시스템에서 SQL Server 쿼리를 실행하기 위한 여러 가지 방법을 제공합니다. 한 가지 다목적 접근 방식은 .NET의 기본 제공 클래스를 활용하여 데이터베이스에 액세스하는 것입니다.

다음 PowerShell 함수인 Invoke-SQL을 사용하면 SQL Server 인스턴스에 대해 임의 쿼리를 실행할 수 있습니다.

function Invoke-SQL {
    param(
        [string] $dataSource = ".\SQLEXPRESS",
        [string] $database = "MasterData",
        [string] $sqlCommand = $(throw "Please specify a query.")
      )

    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    $connection.Close()
    $dataSet.Tables
}
로그인 후 복사

이 함수를 사용하여 쿼리를 실행하려면:

  1. $dataSource, $database 및 $sqlCommand를 특정 값으로 지정하세요.
  2. 수정된 매개변수로 함수를 호출하세요.

예를 들어, 로컬 인스턴스에서 "SELECT * FROM Customers" 쿼리를 실행하려면 " Northwind" 데이터베이스:

$results = Invoke-SQL -Database 'Northwind' -SqlCommand "SELECT * FROM Customers"
로그인 후 복사

$results 변수에는 쿼리 결과가 포함된 테이블 개체가 포함됩니다.

위 내용은 PowerShell에서 SQL Server 쿼리를 어떻게 실행할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿