2017-11-24 9 views
-1

C# VS 2015 프로그램에서 작업 중입니다. 내 프로그램에서 특정 버튼을 클릭하여 작업 수행 중임을 알리는 메시지를 생성하는 큰 텍스트 표시 상자가 있습니다.SQL 서버에서 프로그램으로 행 수 표시

어쨌든 일부 테이블에는 COUNT에 대한 쿼리가있는 SQL 스크립트가 있습니다. 내 프로그램을 통해 그 스크립트를 실행할 수 있습니다. 그러나 행 수는 테이블에 대한 총 행 수를 표시하며 SQL 서버 내에서만 볼 수 있습니다. 내 스크립트를 실행하고 큰 텍스트 디스플레이 박스에서 내 프로그램 내에 ROW COUNTS를 표시하는 방법이 있는지 궁금합니다. 여기

/* open sql connection to execute SQL script: Row count script*/ 
    try 
    { 
     using (SqlConnection con = new SqlConnection(constr)) 
     { 
      con.Open(); 
      FileInfo file = new FileInfo(DIRECTORY OF THE SCRIPT); 
      string script = file.OpenText().ReadToEnd(); 
      Server server = new Server(new ServerConnection(con)); 
      server.ConnectionContext.ExecuteNonQuery(script); 
      Display("ABCDG"); -- to display message on text display 
      con.Close(); 



     } 

    } 
    catch (Exception ex) 
    { 

     textBox1.AppendText(string.Format("{0}", Environment.NewLine)); 
     textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine)); 
     Display(ex.Message + ""); -- display message to textbox 
     textBox1.AppendText(string.Format("{0}", Environment.NewLine)); 
     Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message)); 


    } 

내 프로그램의 스냅 샷입니다 : 여기

는 SQL 스크립트를 실행하려면 코드의 조각입니다 테츠야 야마모토 당신이 무엇인지, 자신의 의견에 말했듯이

https://i.stack.imgur.com/uKP99.png 
+1

와'ExecuteNonQuery는 (스크립트)에서 스크립트 것입니다;'은? – derloopkat

+0

스크립트는 행 수 목록을 포함합니다. 예를 들어 표 A에서 개수 (*)를 선택하고 표 B에서 개수 (*)를 선택하십시오. –

+0

A_Name_Does_Not_Matter이를 수행하는 방법을 명확히 할 수 있습니까? –

답변

1

을 처리하는 방법을 잘 모르는 나처럼 캐스트 ToString는 안전을 위해 단지이다

 int numOfRows = (int)server.ConnectionContext.ExecuteScalar(script); 
    string displayText = numOfRows.ToString(); 
    Display(displayText); -- to display message on text display 
    con.Close(); 

아래

같은 것을 보일 수 있습니다 아래의 T-SQL에 표시된대로 @rowsAffected 변수로 스크립트를 향상시켜야합니다. 그런 다음 C# 코드에서 ExecuteScalar을 호출하여 스크립트의 영향을받는 자세한 행을 가져와야합니다.

**Script file with @rowsAffected variable logic** 

--add following variable at start of your script 
DECLARE @rowsAffected VARCHAR(2000); 

INSERT INTO [dbo].[Products] ([ProductName]) VALUES ('sun1'),('sun2'),('sun3'); 

--after each query that you want to track, include the following line 
SET @rowsAffected = 'Products : ' + CAST(@@rowcount AS varchar(20)); 

UPDATE [dbo].[newTable] SET [ColB] = 'b' ,[ColC] = 'd',[ColD] = 'e' ,[ColE] = 'f' WHERE ColA='a'; 

--after each query that you want to track, include the following line 
SET @rowsAffected = @rowsAffected + ', newTable : ' + CAST(@@rowcount AS varchar(20)); 

-- add the query below at end of your script 
SELECT @rowsAffected; 

당신은 당신이 당신의 코드에서하고있는 바와 같이, 스크립트 파일에서 텍스트를 읽을 수 있고, 다음 아래 코드에서 코드를 실행하기 전에 파일에서 읽은 텍스트를 사용하여 명령 객체를 생성합니다.

C# 코드는 원래의 코드를 사용하여

string rowsAffected =(string) command.ExecuteScalar(); 
//you can now use rowsAffected variable in any way you like 
//it will contain something like Table1 : 4, Table2 : 6 

자세한 C# 코드 스크립트보다 실행하기

using (SqlConnection con = new SqlConnection(constr)) 
    { 

     FileInfo file = new FileInfo(DIRECTORY OF THE SCRIPT); 
     string script = file.OpenText().ReadToEnd(); 

     SqlCommand command = new SqlCommand(script, con); 
     command.CommandType = CommandType.Text; 
     try 
     { 
      con.Open(); 
      string rowsAffected =(string) command.ExecuteScalar(); 
      Display(rowsAffected); 
      con.Close(); 
     } 
     catch (Exception ex) 
     { 
      con.Close(); 
      Display(ex.Message); 
     } 
    } 
+0

설명은 확장 토론이 아닙니다. 이 대화는 [채팅으로 이동되었습니다] (http://chat.stackoverflow.com/rooms/160002/discussion-on-answer-by-sunil-displaying-row-count-from-sql-server-to-program) . – Andy

0

찾고있는 것은 ExecuteScalar 메서드를 사용하는 것입니다. 귀하의 코드 변경, 난 당신이 스크립트 파일에 여러 쿼리가있는 경우 디스플레이가 int 값

+0

예,하지만 OP는 그가 한 번의 선택 카운트가 아니라 해당 스크립트에서 여러 개의 카운트 쿼리를 실행하고 있다고 제안합니다. – derloopkat

+0

나는 이것이 내가 할 수있는 방법 중 하나이지만 내 상황에서는 그렇지 않다는 것을 완전히 알고있다. 내 프로그램의 스냅 샷을 볼 수 있습니다. 왼쪽에는 큰 텍스트 상자가 표시됩니다. 내 목표는 버튼을 만드는 것입니다.이 버튼을 누르면이 스크립트가 실행됩니다. 스크립트 이름은 countrow.sql입니다. 그런 다음 스크립트 내에서 다른 테이블에 대한 레코드 계산에 대한 많은 쿼리가 있지만 이는 문제가 아닙니다. 결과를 SQL 서버의 결과 화면에 어떻게 표시하는지와 마찬가지로 결과를 텍스트 상자에 실시간으로 표시하려고합니다. ExecuteScarlar 메서드는이 작업을 수행하지 않습니다. –