https://github.com/samorysundjata/tsql
Exemplo do post para tabela associativa em T-SQL
https://github.com/samorysundjata/tsql
sql sqlserver tsql
Last synced: 4 months ago
JSON representation
Exemplo do post para tabela associativa em T-SQL
- Host: GitHub
- URL: https://github.com/samorysundjata/tsql
- Owner: samorysundjata
- License: mit
- Created: 2024-09-04T16:34:31.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2024-10-18T15:11:04.000Z (over 1 year ago)
- Last Synced: 2025-10-19T02:59:08.210Z (8 months ago)
- Topics: sql, sqlserver, tsql
- Language: TSQL
- Homepage: https://samory.sistemasresponsivos.com.br/2024/07/28/t-sql-laco-para-popular-tabela-associativa/
- Size: 11.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# T-SQL: Laço para Popular Tabela Associativa
[](https://docs.microsoft.com/en-us/sql/t-sql/language-reference)


Publicado em julho 28, 2024 por Samory Sundjata
Uma tabela associativa implementa relacionamentos muitos-para-muitos entre tabelas/classes, armazenando pares de chaves estrangeiras. Veja como usar um laço para popular tabela associativa em T-SQL.
## O que é T-SQL?
Transact-SQL é uma extensão proprietária da Microsoft para SQL, que adiciona recursos como programação procedural, variáveis locais e manipulação de exceções, sendo usada para gerenciar e consultar dados em bancos de dados SQL Server.
## Exemplo de Tabelas
### Tabelas Principais:
**Estudantes**
- EstudanteID (Chave Primária)
- NomeEstudante
**Cursos**
- CursoID (Chave Primária)
- NomeCurso
### Tabela Associativa:
**EstudantesCursos**
- EstudanteID (Chave Estrangeira, referencia Estudantes.EstudanteID)
- CursoID (Chave Estrangeira, referencia Cursos.CursoID)
### Exemplo de Dados:
**Estudantes**
| EstudanteID | NomeEstudante |
|-------------|---------------|
| 1 | Alice |
| 2 | Beto |
**Cursos**
| CursoID | NomeCurso |
|---------|-------------|
| 101 | Matemática |
| 102 | Literatura |
**EstudantesCursos**
| EstudanteID | CursoID |
|-------------|---------|
| 1 | 101 |
| 1 | 102 |
| 2 | 101 |
## Laço para Popular a Tabela Associativa
```sql
DECLARE @counter INT = (SELECT TOP 1 ID_TABELAMAIOR FROM TABELAMAIOR);
DECLARE @counterMAJ INT = (SELECT COUNT(*) FROM [TABELAMAIOR]);
DECLARE @counterMIN INT = (SELECT COUNT(*) FROM [TABELAMENOR]);
DECLARE @RandomNumber INT = (SELECT ABS(CHECKSUM(NEWID())) % @counterMIN + 1);
WHILE @counter <= @counterMAJ
BEGIN
INSERT INTO [TABELAMAIOR_TABELAMENOR] ([ID_TABELAMAIOR], [ID_TABELAMENOR])
VALUES (@counter, @RandomNumber);
SET @counter = @counter + 1;
SET @RandomNumber = (SELECT ABS(CHECKSUM(NEWID())) % @counterMIN + 1);
END;
```