728x90

두 날짜 사이의 날짜를 선택하는 SQL 쿼리sql


 Answers

지정된 시간 세그먼트가없는 날짜 시간은 date 00:00:00.000 의 값을 갖기 때문에 범위의 모든 날짜를 가져 오려면 종료 날짜의 시간을 제공하거나 종료 날짜를 늘려야합니다 < 사용하십시오.

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'

또는

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date < '2011/02/28'

또는

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'

시간이 00 : 00 : 00.000이면 2011/02/28의 일부 기록을 반환 할 수 있으므로 다음을 사용하지 마십시오.

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date between '2011/02/25' and '2011/02/28'
 Question

start_date 및 end_date 있습니다. 이 두 날짜 사이에 날짜 목록을 가져오고 싶습니다. 누군가 내 쿼리에서 실수를 지적하도록 도와 줄 수 있습니까?

select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and Date between 2011/02/25 and 2011/02/27

여기서 Date 는 datetime 변수입니다.




select * from table_name where col_Date between '2011/02/25' 
AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))

여기에 현재 endDate에 하루를 추가하면 2011-02-28 00:00:00 이되고 종료 날짜를 지정하려면 1 초를 뺍니다 2011-02-27 23:59:59 . 이렇게하면 주어진 간격 사이의 모든 날짜를 가져올 수 있습니다.

output:
2011/02/25
2011/02/26
2011/02/27



select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

- 데이터 형이 다른 경우




# # 사이에 날짜를 넣어보십시오 :

#2013/4/4# and #2013/4/20#

그것은 나를 위해 일했습니다.




현재 날짜와 지난 3 일 사이의 선택 날짜에 대한 최상의 쿼리 :

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN       
DATE_SUB(CURDATE(), INTERVAL 3 DAY)  AND CURDATE() 

현재 날짜와 다음 3 일 사이의 선택 날짜에 대한 최상의 쿼리 :

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN   
   CURDATE()  AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)   



아래를 확인하십시오. 예 : 근무 중이거나 비 근무 중입니다.

select * from tblUser Where    
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**

또는

select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**

또는

select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30')) 
//--**Working**

아래가 작동하지 않습니다.

select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >=  Convert(Varchar(10),'01-01-2015',111) and  Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**


select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**



저는 '1 MonthName 2015'구문에 대해 날짜를 사용하고 싶습니다. 예 :

   WHERE aa.AuditDate>='1 September 2015'
     AND aa.AuditDate<='30 September 2015'

날짜


728x90

i've compiled mysql from source 5.5.24 and now i cannot run mysqltunner.
any idea?

@ghost ghost assigned major on 19 Jun 2012

@major
Owner

major commented on 19 Jun 2012

Try running:

which mysqladmin

If that doesn't work, try:

find / -name mysqladmin -type f

MySQLTuner checks for the mysqladmin executable in your path to see if it's installed.

@ch4mpignator

well,
it's stored in /usr/local/mysql/bin/mysqladmin.

my $command = /usr/local/mysql/bin/mysqladmin; - didn't solve my problem.

@TJM

TJM commented on 19 Jun 2012

PATH=$PATH:/usr/local/mysql/bin

@ch4mpignator

ok it works now!

@FaithNoMango

Apart from [!!] Unable to find mysqladmin in your $PATH. Is MySQL installed? it also says... 'which' is not recognized as an internal or external command, and I added mysql/bin to the path

@pllllllllll

I receive the same error ''Unable to find mysqladmin in your $PATH. Is MySQL installed?'

MySQL is on a stand alond server, seperate from my Windows//IIS webserver. What should my PATH look like, do I need the ip address of the database server ie PATH=$PATH:111.222.333.444//usr/local/mysql/bin ? Or should I install and run mysql tuner on the stand alone database server instead?

@TJM

TJM commented on 21 Nov 2013

mysqltuner should be run on the database server.

@pureche

i still dont get it, where should i put PATH=$PATH:/usr/local/mysql/bin?

i've tried

my $command = PATH=$PATH:/usr/local/mysql/bin;

but it says

Global symbol "$PATH" requires explicit package name at ./mysqltuner.pl line 252.
Execution of ./mysqltuner.pl aborted due to compilation errors (#1)

im a complete noob at this, please help me.

i used find / -name mysqladmin -type f, and the path is /usr/local/mysql/bin/mysqladmin

@major
Owner

major commented on 22 Feb 2014

Sorry for the long delay on this issue. You can use the --mysqladmin flag to specify the path to your custom path if needed:

  # perl mysqltuner.pl --help

     MySQLTuner 1.2.0 - MySQL High Performance Tuning Script
     Bug reports, feature requests, and downloads at http://mysqltuner.com/
     Maintained by Major Hayden (major@mhtx.net) - Licensed under GPL

     Important Usage Guidelines:
        To run the script with the default options, run the script without arguments
        Allow MySQL server to run for at least 24-48 hours before trusting suggestions
        Some routines may require root level privileges (script will provide warnings)
        You must provide the remote server's total memory when connecting to other servers

     Connection and Authentication
        --host <hostname>    Connect to a remote host to perform tests (default: localhost)
        --socket <socket>    Use a different socket for a local connection
        --port <port>        Port to use for connection (default: 3306)
        --user <username>    Username to use for authentication
        --pass <password>    Password to use for authentication
        --mysqladmin <path>  Path to a custom mysqladmin executable


'DB' 카테고리의 다른 글

List stored procedures in MySQL  (0) 2018.05.05
두 날짜 사이의 날짜를 선택하는 SQL 쿼리sql  (0) 2018.04.26
SQL Database Performance Tuning for Developers  (0) 2018.04.10
[MSSQL]sqlsrv_fetch_array  (0) 2018.02.05
[MSSQL]sqlsrv_execute  (0) 2018.02.05
728x90

SQL performance tuning can be an incredibly difficult task, particularly when working with large-scale data where even the most minor change can have a dramatic (positive or negative) impact on performance.

In mid-sized and large companies, most SQL performance tuning will be handled by a Database Administrator (DBA). But believe me, there are plenty of developers out there who have to perform DBA-like tasks. Further, in many of the companies I’ve seen that do have DBAs, they often struggle to work well with developers—the positions simply require different modes of problem solving, which can lead to disagreement among coworkers.

When working with large-scale data, even the most minor change can have a dramatic impact on performance.

On top of that, corporate structure can also play a role. Say the DBA team is placed on the 10th floor with all of their databases, while the devs are on the 15th floor, or even in a different building under a completely separate reporting structure—it’s certainly hard to work together smoothly under these conditions.  In this article, I’d like to accomplish two things:

  1. Provide developers with some developer-side SQL performance tuning techniques.
  2. Explain how developers and DBAs can work together effectively.

SQL Performance Tuning (in the Codebase): Indexes

If you’re a complete newcomer to databases and even asking yourself “What is SQL performance tuning?”, you should know that indexing is an effective way to tune your SQL database that is often neglected during development. In basic terms, an index is a data structure that improves the speed of data retrieval operations on a database table by providing rapid random lookups and efficient access of ordered records. This means that once you’ve created an index, you can select or sort your rows faster than before.

Indexes are also used to define a primary-key or unique index which will guarantee that no other columns have the same values. Of course, database indexing is a vast an interesting topic to which I can’t do justice with this brief description (but here’s a more detailed write-up).

If you’re new to indexes, I recommend using this diagram when structuring your queries: This diagram illustrates a few SQL performance tuning tips every developer should know.

Basically, the goal is to index the major searching and ordering columns.

Note that if your tables are constantly hammered by INSERTUPDATE, and DELETE, you should be careful when indexing—you could end up decreasing performance as all indexes need to be modified after these operations.

Further, DBAs often drop their SQL indexes before performing batch inserts of million-plus rows to speed up the insertion process. After the batch is inserted, they then recreate the indexes. Remember, however, that dropping indexes will affect every query running in that table; so this approach is only recommended when working with a single, large insertion.

SQL Tuning: Execution Plans in SQL Server

By the way: the Execution Plan tool in SQL Server can be useful for creating indexes.

Its main function is to graphically display the data retrieval methods chosen by the SQL Server query optimizer. If you’ve never seen them before, there’s a detailed walkthrough.

To retrieve the execution plan (in SQL Server Management Studio), just click “Include Actual Execution Plan” (CTRL + M) before running your query.

Afterwards, a third tab named “Execution Plan” will appear. You might see a detected missing index. To create it, just right click in the execution plan and choose the “Missing Index Details…”. It’s as simple as that!

This screenshot demonstrates one of the performance tuning techniques for your SQL database.

(Click to zoom)

SQL Tuning: Avoid Coding Loops

Imagine a scenario in which 1000 queries hammer your database in sequence. Something like:

for (int i = 0; i < 1000; i++)
{
    SqlCommand cmd = new SqlCommand("INSERT INTO TBL (A,B,C) VALUES...");
    cmd.ExecuteNonQuery();
}

You should avoid such loops in your code. For example, we could transform the above snippet by using a unique INSERT or UPDATE statement with multiple rows and values:

INSERT INTO TableName (A,B,C) VALUES (1,2,3),(4,5,6),(7,8,9) -- SQL SERVER 2008

INSERT INTO TableName (A,B,C) SELECT 1,2,3 UNION ALL SELECT 4,5,6 -- SQL SERVER 2005

UPDATE TableName SET A = CASE B
        WHEN 1 THEN 'NEW VALUE'
        WHEN 2 THEN 'NEW VALUE 2'
        WHEN 3 THEN 'NEW VALUE 3'
    END
WHERE B in (1,2,3)

Make sure that your WHERE clause avoids updating the stored value if it matches the existing value. Such a trivial optimization can dramatically increase SQL query performance by updating only hundreds of rows instead thousands. For example:

UPDATE TableName
SET A = @VALUE
WHERE
      B = 'YOUR CONDITION'
            AND A <> @VALUE -- VALIDATION

SQL Tuning: Avoid Correlated SQL Subqueries

correlated subquery is one which uses values from the parent query. This kind of SQL query tends to run row-by-row, once for each row returned by the outer query, and thus decreases SQL query performance. New SQL developers are often caught structuring their queries in this way—because it’s usually the easy route.

Here’s an example of a correlated subquery:

SELECT c.Name, 
       c.City,
       (SELECT CompanyName FROM Company WHERE ID = c.CompanyID) AS CompanyName 
FROM Customer c

In particular, the problem is that the inner query (SELECT CompanyName…) is run for each row returned by the outer query (SELECT c.Name…). But why go over the Company again and again for every row processed by the outer query?

A more efficient SQL performance tuning technique would be to refactor the correlated subquery as a join:

SELECT c.Name, 
       c.City, 
       co.CompanyName 
FROM Customer c 
	LEFT JOIN Company co
		ON c.CompanyID = co.CompanyID

In this case, we go over the Company table just once, at the start, and JOIN it with the Customer table. From then on, we can select the values we need (co.CompanyName) more efficiently.

SQL Tuning: Select Sparingly

One of my favorite SQL optimization tips is to avoid SELECT *! Instead, you should individually include the specific columns that you need. Again, this sounds simple, but I see this error all over the place. Consider a table with hundreds of columns and millions of rows—if your application only really needs a few columns, there’s no sense in querying for all the data. It’s a massive waste of resources. (For more issues, see here.)

For example:

SELECT * FROM Employees

vs.

SELECT FirstName, City, Country FROM Employees

If you really need every column, explicitly list every column. This isn’t so much a rule, but rather, a means of preventing future system errors and additional SQL performance tuning. For example, if you’re using an INSERT... SELECT... and the source table has changed via the addition of a new column, you might run into issues, even if that column isn’t needed by the destination table, e.g.:

INSERT INTO Employees SELECT * FROM OldEmployees

Msg 213, Level 16, State 1, Line 1
Insert Error: Column name or number of supplied values does not match table definition.

To avoid this kind of error from SQL Server, you should declare each column individually:

INSERT INTO Employees (FirstName, City, Country)
SELECT Name, CityName, CountryName
FROM OldEmployees

Note, however, that there are some situations where the use of SELECT * could be appropriate. For example, with temp tables—which leads us to our next topic.

SQL Tuning: The Wise Use of Temporary Tables (#Temp)

Temporary tables usually increase a query’s complexity. If your code can be written in a simple, straightforward manner, I’d suggest avoiding temp tables.

But if you have a stored procedure with some data manipulation that cannot be handled with a single query, you can use temp tables as intermediaries to help you to generate a final result.

When you have to join a large table and there are conditions on said table, you can increase database performance by transferring your data in a temp table, and then making a join on that. Your temp table will have fewer rows than the original (large) table, so the join will finish faster!

The decision isn’t always straightforward, but this example will give you a sense for situations in which you might want to use temp tables:

Imagine a customer table with millions of records. You have to make a join on a specific region. You can achieve this by using a SELECT INTO statement and then joining with the temp table:

SELECT * INTO #Temp FROM Customer WHERE RegionID = 5
SELECT r.RegionName, t.Name FROM Region r JOIN #Temp t ON t.RegionID = r.RegionID

(Note: some SQL developers also avoid using SELECT INTO to create temp tables, saying that this command locks the tempdb database, disallowing other users from creating temp tables. Fortunately, this is fixed in 7.0 and later.)

As an alternative to temp tables, you might consider using a subquery as a table:

SELECT r.RegionName, t.Name FROM Region r 
JOIN (SELECT * FROM Customer WHERE RegionID = 5) AS t 
ON t.RegionID = r.RegionID

But wait! There’s a problem with this second query. As described above, we should only be including the columns we need in our subquery (i.e., not using SELECT *). Taking that into account:

SELECT r.RegionName, t.Name FROM Region r 
JOIN (SELECT Name, RegionID FROM Customer WHERE RegionID = 5) AS t 
ON t.RegionID = r.RegionID

All of these SQL snippets will return the same data. But with temp tables, we could, for example, create an index in the temp table to improve performance. There’s some good discussion here on the differences between temporary tables and subqueries.

Finally, when you’re done with your temp table, delete it to clear tempdb resources, rather than just wait for it to be automatically deleted (as it will be when your connection to the database is terminated):

DROP TABLE #temp

SQL Tuning: “Does My Record Exist?”

This SQL optimization technique concerns the use of EXISTS(). If you want to check if a record exists, use EXISTS() instead of COUNT(). While COUNT() scans the entire table, counting up all entries matching your condition, EXISTS() will exit as soon as it sees the result it needs. This will give you better performance and clearer code.

IF (SELECT COUNT(1) FROM EMPLOYEES WHERE FIRSTNAME LIKE '%JOHN%') > 0
    PRINT 'YES' 

vs.

IF EXISTS(SELECT FIRSTNAME FROM EMPLOYEES WHERE FIRSTNAME LIKE '%JOHN%')
    PRINT 'YES'

SQL Performance Tuning With SQL Server 2016

As DBAs working with SQL Server 2016 are likely aware, the version marked an important shift in defaults and compatibility management. As a major version, it of course comes with new query optimizations, but control over whether they’re used is now streamlined via sys.databases.compatibility_level.

SQL Performance Tuning (in the Office)

SQL database administrators (DBAs) and developers often clash over data- and non-data-related issues. Drawn from my experience, here are some tips (for both parties) on how to get along and work together effectively.

SQL performance tuning goes beyond the codebase when DBAs and developers have to work together effectively.

Like what you're reading?
Get the latest updates first.
No spam. Just great engineering posts.

Database Optimization for Developers:

  1. If your application stops working suddenly, it may not be a database issue. For example, maybe you have a network problem. Investigate a bit before you accuse a DBA!

  2. Even if you’re a ninja SQL data modeler, ask a DBA to help you with your relational diagram. They have a lot to share and offer.

  3. DBAs don’t like rapid changes. This is natural: they need to analyze the database as a whole and examine the impact of any changes from all angles. A simple change in a column can take a week to be implemented—but that’s because an error could materialize as huge losses for the company. Be patient!

  4. Do not ask SQL DBAs to make data changes in a production environment. If you want access to the production database, you have to be responsible for all your own changes.

Database Optimization for SQL Server DBAs:

  1. If you don’t like people asking you about the database, give them a real-time status panel. Developers are always suspicious of a database’s status, and such a panel could save everyone time and energy.

  2. Help developers in a test/quality assurance environment. Make it easy to simulate a production server with simple tests on real-world data. This will be a significant time-saver for others as well as yourself.

  3. Developers spend all day on systems with frequently-changed business logic. Try to understand this world being more flexible, and be able to break some rules in a critical moment.

  4. SQL databases evolve. The day will come when you have to migrate your data to a new version. Developers count on significant new functionality with each new version. Instead of refusing to accept their changes, plan ahead and be ready for the migration.

UNDERSTANDING THE BASICS

What is query processing in a DBMS?

Database management systems like SQL Server have to translate the SQL queries you give them into the actual instructions they have to perform to read or change the data in the database. After processing, the database engine then also attempts to automatically optimize the query where possible.


'DB' 카테고리의 다른 글

두 날짜 사이의 날짜를 선택하는 SQL 쿼리sql  (0) 2018.04.26
PATH=$PATH:/usr/local/mysql/bin;  (0) 2018.04.19
[MSSQL]sqlsrv_fetch_array  (0) 2018.02.05
[MSSQL]sqlsrv_execute  (0) 2018.02.05
jQuery mouseleave()  (0) 2018.01.14
728x90


데이터의 다음 행을 숫자로 인덱싱된 배열, 결합형 배열 또는 둘 다로 검색합니다.

구문


sqlsrv_fetch_array( resource $stmt[, int $fetchType [, row[, ]offset]])  

매개 변수

$stmt: 실행된 문에 해당하는 문 리소스입니다.

$fetchType [선택 사항]: 미리 정의 된 상수입니다. 이 매개 변수는 다음 표에 나열된 값 중 하나를 사용할 수 있습니다.

Description
SQLSRV_FETCH_NUMERIC데이터의 다음 행이 숫자형 배열로 반환됩니다.
SQLSRV_FETCH_ASSOC데이터의 다음 행이 결합형 배열로 반환됩니다. 배열 키는 결과 집합의 열 이름입니다.
SQLSRV_FETCH_BOTH데이터의 다음 행이 숫자형 배열과 결합형 배열 둘 다로 반환됩니다. 이 값은 기본값입니다.

 [선택 사항]: 버전 1.1에에서 추가 합니다. 다음 값 중 하나로 스크롤 가능 커서를 사용하는 결과 집합에서 액세스할 행을 지정합니다. (때  지정 된 fetchtype 명시적으로 지정 해야 기본값을 지정 하는 경우에 합니다.)

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

이러한 값에 대한 자세한 내용은 커서 유형 지정 및 행 선택을 참조하세요. 스크롤 가능 커서 지원이 Microsoft Drivers for PHP for SQL Server의 버전 1.1에 추가되었습니다.

오프셋 [선택 사항]: 검색할 행을 지정 하려면 데 SQLSRV_SCROLL_ABSOLUTE 및 SQLSRV_SCROLL_RELATIVE 함께 사용 합니다. 결과 집합의 첫 번째 레코드는 0입니다.

반환 값

데이터 행이 검색되는 경우 배열 이 반환됩니다. 검색할 행이 더 이상 없는 경우 null 이 반환됩니다. 오류가 발생하면 false 가 반환됩니다.

$fetchType 매개 변수의 값을 기반으로, 반환된 배열 은 숫자로 인덱싱된 배열, 결합형 배열또는 둘 다일 수 있습니다. 기본적으로 숫자 키와 결합형 키가 둘 다 있는 배열 이 반환됩니다. 반환된 배열에 있는 값의 데이터 형식은 기본 PHP 데이터 형식입니다. 기본 PHP 데이터 형식에 대한 자세한 내용은 Default PHP Data Types을 참조하세요.

주의

이름이 없는 열이 반환되면 배열 요소에 대한 결합형 키는 빈 문자열("")입니다. 예를 들어 값을 데이터베이스 테이블에 삽입하고 서버 생성 기본 키를 검색하는 다음 Transact-SQL 문을 고려해 보겠습니다.

INSERT INTO Production.ProductPhoto (LargePhoto) VALUES (?);  
SELECT SCOPE_IDENTITY()

반환 된 결과 집합이 SELECT SCOPE_IDENTITY() 이 문의 부분 결합형 배열로 검색 되 인 반환된 된 값에 대 한 키는 빈 문자열 ("")는 반환 된 열에 이름이 없기 때문에 합니다. 이를 방지하려면 결과를 숫자형 배열로 검색하거나 Transact-SQL 문에서 반환된 열에 대한 이름을 지정할 수 있습니다. 다음은 Transact-SQL에 열 이름을 지정하는 한 가지 방법입니다.

SELECT SCOPE_IDENTITY() AS PictureID

결과 집합에 이름이 없는 여러 열이 포함된 경우 마지막으로 이름이 지정되지 않은 열의 값이 빈 문자열("") 키에 할당됩니다.

예제

다음 예제는 결과 집합의 각 행을 결합형 배열로 검색합니다. 이 예제에서는 SQL Server 및 AdventureWorks 데이터베이스가 로컬 컴퓨터에 설치된 것으로 가정합니다. 모든 출력은 명령줄에서 예제가 실행될 때 콘솔에 기록됩니다.

<?php  
/* Connect to the local server using Windows Authentication and  
specify the AdventureWorks database as the database in use. */  
$serverName = "(local)";  
$connectionInfo = array( "Database"=>"AdventureWorks");  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  
if( $conn === false )  
{  
     echo "Could not connect.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Set up and execute the query. */  
$tsql = "SELECT FirstName, LastName  
         FROM Person.Contact  
         WHERE LastName='Alan'";  
$stmt = sqlsrv_query( $conn, $tsql);  
if( $stmt === false)  
{  
     echo "Error in query preparation/execution.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Retrieve each row as an associative array and display the results.*/  
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))  
{  
      echo $row['LastName'].", ".$row['FirstName']."\n";  
}  

/* Free statement and connection resources. */  
sqlsrv_free_stmt( $stmt);  
sqlsrv_close( $conn);  
?>  

예제

다음 예제는 결과 집합의 각 행을 숫자로 인덱싱된 배열로 검색합니다.

제품 정보를 검색 하는 예제는 Purchasing.PurchaseOrderDetail 지정된 된 날짜와 재고량이 있는 제품에 대 한 AdventureWorks 데이터베이스의 테이블 (StockQty) 지정된 된 값 보다 작습니다.

이 예제에서는 SQL Server 및 AdventureWorks 데이터베이스가 로컬 컴퓨터에 설치된 것으로 가정합니다. 모든 출력은 명령줄에서 예제가 실행될 때 콘솔에 기록됩니다.

<?php  
/* Connect to the local server using Windows Authentication and  
specify the AdventureWorks database as the database in use. */  
$serverName = "(local)";  
$connectionInfo = array( "Database"=>"AdventureWorks");  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  
if( $conn === false )  
{  
     echo "Could not connect.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Define the query. */  
$tsql = "SELECT ProductID,  
                UnitPrice,  
                StockedQty   
         FROM Purchasing.PurchaseOrderDetail  
         WHERE StockedQty < 3   
         AND DueDate='2002-01-29'";  

/* Execute the query. */  
$stmt = sqlsrv_query( $conn, $tsql);  
if ( $stmt )  
{  
     echo "Statement executed.\n";  
}   
else   
{  
     echo "Error in statement execution.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Iterate through the result set printing a row of data upon each  
iteration.*/  
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))  
{  
     echo "ProdID: ".$row[0]."\n";  
     echo "UnitPrice: ".$row[1]."\n";  
     echo "StockedQty: ".$row[2]."\n";  
     echo "-----------------\n";  
}  

/* Free statement and connection resources. */  
sqlsrv_free_stmt( $stmt);  
sqlsrv_close( $conn);  
?>  

sqlsrv_fetch_array 함수에 따라 데이터는 항상 반환 된 기본 PHP 데이터 형식합니다. PHP 데이터 형식을 지정하는 방법에 대한 자세한 내용은 How to: Specify PHP Data Types을 참조하세요.

이름이 없는 필드가 검색되는 경우 배열 요소에 대한 결합형 키는 빈 문자열("")입니다. 자세한 내용은 sqlsrv_fetch_array를 참조하세요.

참고 항목

SQLSRV 드라이버 API 참조
데이터 검색
설명서의 코드 예제 정보
PHP SQL 드라이버 프로그래밍 가이드

'DB' 카테고리의 다른 글

PATH=$PATH:/usr/local/mysql/bin;  (0) 2018.04.19
SQL Database Performance Tuning for Developers  (0) 2018.04.10
[MSSQL]sqlsrv_execute  (0) 2018.02.05
jQuery mouseleave()  (0) 2018.01.14
mysqli_result::fetch_array  (0) 2018.01.14

+ Recent posts