> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201903/untitled-8.md).

# 2019/0320/SQL檢視表\&tsql基礎\&Asp.net\_Gridview

## SQL 檢視表 view

資料庫裡的view視界

有意義的資料稱為資訊

把視界存成一個物件，處理完的產物稱為view檢視表

![](/files/-LaNXfshp87Fsrq4_OWy)

組成檢視表的基底可以是資料表也可以是檢視表

![](/files/-LaNYNBu6dRQfzh_M6Il)

查詢與關聯與取別名都可在這Gui完成

檢視表取名需要特別註記不然會混再一起View學生選課明細/V\_學生選課明細...

### 創建檢視表

```
select * from View學生選課明細含老師名字
where 學分=4
--------------------------------------
--視界(View)
--檢視表(View)

create view View有名字的教授資料
as
select 教授.*, 員工.姓名, 員工.薪水, 員工.電話
from 員工 inner join 教授 on 員工.身份證字號=教授.身份證字號

select * from View有名字的教授資料
```

![](/files/-LaNbKid0uV8Nf5ZxYhE)

```
create view View教授開課資料
as
SELECT          dbo.View有名字的教授資料.姓名, dbo.課程.課程編號, dbo.課程.名稱, dbo.課程.學分
FROM              dbo.班級 INNER JOIN
                            dbo.課程 ON dbo.班級.課程編號 = dbo.課程.課程編號 INNER JOIN
                            dbo.View有名字的教授資料 ON dbo.班級.教授編號 = dbo.View有名字的教授資料.教授編號
							group by dbo.View有名字的教授資料.姓名, dbo.課程.課程編號, dbo.課程.名稱, dbo.課程.學分

select * from View教授開課資料
```

階層如果一直往上容易遺忘，有時候會有效能問題，且如果砍其中一個基底，會造成整個系統GG

### 修改檢視表

等於要重新定義此檢視表等於重寫. . .

```
alter view View教授開課資料
as
SELECT          dbo.View有名字的教授資料.姓名,dbo.View有名字的教授資料.職稱, dbo.課程.課程編號, dbo.課程.名稱, dbo.課程.學分
FROM              dbo.班級 INNER JOIN
                            dbo.課程 ON dbo.班級.課程編號 = dbo.課程.課程編號 INNER JOIN
                            dbo.View有名字的教授資料 ON dbo.班級.教授編號 = dbo.View有名字的教授資料.教授編號
							group by dbo.View有名字的教授資料.姓名,dbo.View有名字的教授資料.職稱, dbo.課程.課程編號, dbo.課程.名稱, dbo.課程.學分
```

### 刪除檢視表

```
drop view View教授開課資料
```

#### dml ddl script 敘述性小程式  較無邏輯性

不代表資料庫本身沒有程式語言

## T-SQL&#x20;

#### MYSQL - TSQL

#### ACCESS -VBA

#### 歐洛扣 PL-SQL

預存程序 交易處理 函式 都是有邏輯性存在的 迴圈  IF 敘述

只講語法 然後 實作

### 基本語法與純數變量

字串要用單引號 裡面的字紅色顯示

```
print 'hello world!!'
```

每一個語言提供的變數資料型態與定義不同

純量變數 相較於其他程式語言沒有

純量變數 : 裡面存的東西為一個值

資料表變數 : 存資料表

### 純量變數

宣告變數

宣告 名稱 資料型態

```
declare @MyString varchar(50) ='hello world!!'
declare @number int
set @number=100
select @number=200

print @mystring
print @NUMBER
```

宣告時給值 = 宣告時即初始化

```
declare @name varchar(20) ='王大明'
declare @Salary money =50000
print @Name+'的薪水為'+ cast(@Salary as varchar)+'元'
go
```

加法運算 必須轉換相同資料型態

沒有分號與斷點所以必須用 go 同時可以決定區域變數

轉換資料型態也可轉換資料顯示

```
declare @name varchar(20) ='王小明'
declare @birthday datetime ='2000/1/1'
print @Name+'的生日是'+ cast(@birthday as varchar)
print @Name+'的生日是'+ convert(varchar,@birthday,111)
print @Name+'的生日是'+ replace(convert(varchar,@birthday,111),'/','-')

select 姓名,replace(convert(varchar,生日,111),'/','-') from 學生
```

null 可以存在於任何型態 但需要花資源去維護

t-sql 程式的好處   資料庫端 是可以連同資料一起使用

連 select 也能宣告變數

```
declare @name varchar(20), @birthday datetime

select @name=姓名, @birthday=生日 from 學生
where 學號='S003'

print @name
print @birthday
go

declare @name varchar(20), @birthday datetime

--select 姓名, 生日 from 學生
select @name=姓名, @birthday=生日 from 學生

print @name
print @birthday
go
```

不只一筆資料儲存在一個變數時會怎樣? 只會儲存最後一筆變數

所以才需要資料表變數

### 資料表變數

```
--資料表變數
declare @Student_Birthday table(
	name varchar(20),
	birthday datetime
)
insert into @Student_Birthday
select 姓名, 生日 from 學生


select * from @Student_Birthday
```

資料表變數不管幾筆都進得去 但是要開始定義資料表與欄位

把資料表變數當成資料表用

###

###

###

## asp.net元件

### 購物車將資料庫資料導入

為什麼buttonfield看起來像超鏈結?

asp.net有三種按鈕但是物件方法差不多

button 元件

linkbutton 元件&#x20;

ingebutton 元件

buttontype 屬性 =使用button就會變成按鈕外觀

commandname 屬性 : 按下按鈕時觸發底下事件 這個是拿來識別命令的名稱

onrawcommand 屬性 : 事件發生時呼叫的函式名稱

```
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MySystemConnectionString1 %>" SelectCommand="SELECT * FROM [Products]"></asp:SqlDataSource>
⁂⁂⁂⁂⁂  <asp:GridView  CssClass="table table-hover" ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
OnRowCommand="ShowOrderList">
<Columns>
<asp:BoundField DataField="Product_ID" HeaderText="Product_ID" SortExpression="Product_ID" />
<asp:BoundField DataField="Product_Name" HeaderText="Product_Name" SortExpression="Product_Name" />
<%--  <asp:BoundField DataField="Product_Img" HeaderText="Product_Img" SortExpression="Product_Img" />--%>
 <asp:ImageField DataImageUrlField="Product_Img" DataImageUrlFormatString="~\ProductsImg\s{0}"></asp:ImageField>
 <asp:BoundField DataField="Product_Price" DataFormatString="{0:C0}" HeaderText="Product_Price" SortExpression="Product_Price" />
 <asp:BoundField DataField="Product_price2" DataFormatString="{0:C0}" HeaderText="Product_price2" SortExpression="Product_price2" />
 <%--<asp:BoundField DataField="Product_Intro" HeaderText="Product_Intro" SortExpression="Product_Intro" />--%>
 <asp:TemplateField HeaderText="Product_Intro" SortExpression="Product_Intro">
 <EditItemTemplate>
 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Product_Intro") %>'></asp:TextBox>
 </EditItemTemplate>
 <ItemTemplate>
⁂⁂⁂⁂⁂  <asp:Label ID="Label1" runat="server" Text='<%# Eval("Product_Intro").ToString().Replace("\n","<br>") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CheckBoxField DataField="Product_Status" HeaderText="Product_Status" SortExpression="Product_Status" />
⁂⁂⁂⁂⁂  <asp:ButtonField Text="加入購物車" ButtonType="Button" CommandName="Order" />
</Columns>
</asp:GridView>

<asp:Label ID="lblCar" runat="server"></asp:Label>
```

e.commandargument 命令引數並轉換資料型態丟到index變數中

gridview1.rows\[index].cells\[1].text 抓品名丟到其他盒子去做顯示

```
protected void ShowOrderList(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Order")
{
int index=Convert.ToInt32(e.CommandArgument);

 lblCar.Text += GridView1.Rows[index].Cells[1].Text+" 已經加入購物車<br />";
}
           
}
```

+= 累加的才會累加顯示

### hyperlinkfield 用法

公開資料庫 json檔案

user interface&#x20;

資料介接 api  拋回來的資料

![](/files/-LaOl4hYtH21Hd9s9aHi)

http協定傳定訊息的方法為 url (厲害的人可以用url 傳遞惡意程式

![](/files/-LaOlB48DjE6jYZh48IF)

post&#x20;

get (url) 把資料帶在網址後面

通常給api的網頁會寫url api文件要怎寫

![](/files/-LaOlGyEUzKOAI2Iqko5)

看到什麼資料全靠url後面帶的參數

路徑的設定

牽涉到seo上的排名

http協定靠url傳遞參數讓我們得到不同的答案

###

### 點擊個人名稱進入個人資料

```
<asp:BoundField DataField="Account" HeaderText="Account" ReadOnly="True" SortExpression="Account" />          
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />


<asp:HyperLinkField DataTextFormatString="詳細資料" 
DataTextField="Account" 
DataNavigateUrlFormatString="23GridView_HyperLinkField-2.aspx?id={0}&n={1}" 
DataNavigateUrlFields="Account,Name" />
```

hyperlinkfield 屬性必須設定完整後才會有作用

Data Text Field 數據文本字段

Account 帳戶

Data Navigate Url Format String 數據導航URL格式字符串

```
-2.aspx?id={0}&n={1}"
```

keyvalue 索引位置

#### HyperLinkField-2

### 以傳遞過來的帳號查詢個人資料

```
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MySystemConnectionString1 %>" 
SelectCommand="SELECT * FROM [Members] where Account=@Account">
<SelectParameters>
<asp:QueryStringParameter Name="Account" Type="String" QueryStringField="id" />
</SelectParameters>
```

querystringparameter 變數值在網址上使用此控制項

![](/files/-LaOoqPc_shNhlT7Bsf4)

?後面為網址上的欄位

QueryStringField : 取得或設定參數所繫結至的查詢字串欄位名稱。

{% embed url="<https://docs.microsoft.com/zh-tw/dotnet/api/system.web.ui.webcontrols.querystringparameter.querystringfield?view=netframework-4.7.2>" %}

### gridview元件 本身沒有提供新增功能  只能修改跟刪除 其他的view才有

而新增修改刪除必須使用

`commandfield 元件`

```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
DataKeyNames="Account" DataSourceID="SqlDataSource1" 
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
```

AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"

預設修改 預設刪除&#x20;

問題1.按鈕位置固定且為鏈結紐

現在回寫資料庫必須用sql語法

### commandfield 自定義新增修改刪除按鈕

```
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" ButtonType="Button" />
```

### 實務上girdview應用

```
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:MySystemConnectionString1 %>" 
                SelectCommand="SELECT * FROM [Members]"
                 UpdateCommand="update Members set Name=@Name,  Email=@Email, EduLevel=@EduLevel, Notes=@Notes where Account=@Account"
                ></asp:SqlDataSource>

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Account" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="Account" HeaderText="Account" ReadOnly="True" SortExpression="Account" />
                    <asp:BoundField DataField="Pswd" HeaderText="Pswd" SortExpression="Pswd" ReadOnly="true" DataFormatString="******" />
                    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                    <asp:BoundField DataField="Birthday" HeaderText="Birthday" SortExpression="Birthday" ReadOnly="true" />
                    <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                    <asp:CheckBoxField DataField="Gender" HeaderText="Gender" SortExpression="Gender" ReadOnly="true" />
                    <asp:BoundField DataField="EduLevel" HeaderText="EduLevel" SortExpression="EduLevel" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:CommandField ShowEditButton="true" ShowDeleteButton="true" ButtonType="Button" />

                </Columns>
            </asp:GridView>
```

### gridview新增修改刪除時，實務上會出現很多問題

管理者介面如果能夠新增修改刪除也需要下驗證器不然資料型態錯誤就會出現資料庫錯誤

```
<asp:CheckBoxField DataField="Gender" HeaderText="Gender" SortExpression="Gender" 
   ReadOnly="true" />
   <asp:BoundField DataField="Birthday" HeaderText="Birthday" SortExpression="Birthday" 
   ReadOnly="true" />
```

以上兩種都會造成修改問題

不然就要設置 readonly 密碼 地址 姓名等等 根據系統不同有不同的存取方式

程式沒錯 式資料庫或是其他地方錯 所以就會出現 exception

新增修改刪除 vs與sql已經data by ding 不用設定參數 已datasolus繫結了

#### 所以看的出來 gridview 實務上只能做刪除跟上下架

![](/files/-LaP68cYbeNjtAkYs70G)

### 實務上刪除功能

![](/files/-LaP7Z41tzxl1HK0noit)

實務上刪除絕對要下where不然整個資料庫會被刪除

ui/

ux 經驗化直覺化

除了where還要出現提示眶要去認刪除才能真的深除

利用js來下指令

arent 只有確認的提示框

comfon才會試確認取消框

但控制項沒有  button id

所以利用 c#來寫

```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Account" 
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
```

OnRowCommand 去抓後端功能來秀

![](/files/-LaPCmXDdJJowRkI22nU)

轉成button物件後才能操作他

必須要抓取確定或取消

必須避開欄位名稱(第一欄) if

唯有刪除紐才要埋設confirm

```
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                if(((Button)e.Row.Cells[8].Controls[2]).CommandName=="Delete")
                    ((Button)e.Row.Cells[8].Controls[2]).Attributes["onclick"] = "if(!confirm('您確定要刪除【"+e.Row.Cells[2].Text+"】的資料嗎??????')) return;";
            }
        }
```

c#必須編譯過才能看

c# commandname 是固定的 delete edit update new insert select cancel


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201903/untitled-8.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
