#include 'protheus.ch'
#include 'tbiconn.ch'

User Function SQAMat()

    //PREPARE ENVIRONMENT EMPRESA 'T1' FILIAL 'D MG 01 ' // Utilizado para chamar diretamente a função

	Private nStatus  := 0
	Private cQuery   := ""
    Private cQuery2  := ""

    cQuery := " UPDATE " + RetSqlName( "TM5" )
	cQuery += " SET TM5_MAT = ("
	cQuery += " SELECT TM0.TM0_MAT FROM " + RetSQLName( "TM0" ) + " TM0 "
	cQuery += " WHERE TM0.TM0_FILIAL = TM0.TM0_FILIAL"
	cQuery += " AND TM0.TM0_NUMFIC = TM5_NUMFIC"
    cQuery += " AND TM0.TM0_MAT IS NOT NULL"
	cQuery += " AND TM0.D_E_L_E_T_ = ' ' )"
	cQuery += " WHERE TM5_FILIAL = TM5_FILIAL" 
	cQuery += " AND TM5_MAT = ' '"
	cQuery += " AND D_E_L_E_T_ = ' '"
	TCSQLExec( cQuery )

    cQuery2 := " UPDATE " + RetSqlName( "TM5" )
	cQuery2 += " SET TM5_FILFUN = ("
	cQuery2 += " SELECT TM0.TM0_FILFUN FROM " + RetSQLName( "TM0" ) + " TM0 "
	cQuery2 += " WHERE TM0.TM0_FILIAL = TM0.TM0_FILIAL"
	cQuery2 += " AND TM0.TM0_NUMFIC = TM5_NUMFIC"
	cQuery2 += " AND TM0.D_E_L_E_T_ = ' ' )"
	cQuery2 += " WHERE TM5_FILIAL = TM5_FILIAL" 
	cQuery2 += " AND TM5_FILFUN = ' '"
	cQuery2 += " AND TM5_MAT <> ' '"
	cQuery2 += " AND D_E_L_E_T_ = ' '"
	TCSQLExec( cQuery2 )

	If nStatus >= 0
		Help( Nil, Nil, "Atenção", Nil, "Operação realizada com sucesso!" , 1, 0 )
	ElseIf nStatus < 0  // Caso a query não foi executada corretamente.
		Help( Nil, Nil, "Atenção", Nil, TcSQLError() , 1, 0 ) // Atenção
	EndIf

    //RESET ENVIRONMENT // Utilizado para chamar diretamente a função

Return
