internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: tobymao/sqlglot

Issue:
DELETE USING not supported
Parsing a statement such as:

```sql
delete from event using sales where event.eventid=sales.eventid;
```
taken from https://docs.aws.amazon.com/redshift/latest/dg/r_DELETE.html
fails with:
```
ERROR: Invalid expression / Unexpected token. Line 1, Col: 19.
```


Discussion:

Resolving patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -729,7 +729,7 @@ class Constraint(Expression):
 
 
 class Delete(Expression):
-    arg_types = {"with": False, "this": True, "where": False}
+    arg_types = {"with": False, "this": True, "using": False, "where": False}
 
 
 class Drop(Expression):
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -423,8 +423,11 @@ def directory_sql(self, expression):
 
     def delete_sql(self, expression):
         this = self.sql(expression, "this")
+        using_sql = (
+            f" USING {self.expressions(expression, 'using', sep=', USING ')}" if expression.args.get("using") else ""
+        )
         where_sql = self.sql(expression, "where")
-        sql = f"DELETE FROM {this}{where_sql}"
+        sql = f"DELETE FROM {this}{using_sql}{where_sql}"
         return self.prepend_ctes(expression, sql)
 
     def drop_sql(self, expression):
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -925,6 +925,7 @@ def _parse_delete(self):
         return self.expression(
             exp.Delete,
             this=self._parse_table(schema=True),
+            using=self._parse_csv(lambda: self._match(TokenType.USING) and self._parse_table(schema=True)),
             where=self._parse_where(),
         )
 


Test patch:
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -513,6 +513,8 @@ ALTER TYPE electronic_mail RENAME TO email
 ANALYZE a.y
 DELETE FROM x WHERE y > 1
 DELETE FROM y
+DELETE FROM event USING sales WHERE event.eventid = sales.eventid
+DELETE FROM event USING sales, USING bla WHERE event.eventid = sales.eventid
 DROP TABLE a
 DROP TABLE a.b
 DROP TABLE IF EXISTS a
Repository: tobymao/sqlglot

Issue:
Support special syntax of limit & offset for ClickHouse
Hello guys! How are you?

Current version of apache/superset generates sql with `LIMIT 10, 20` instead of `LIMIT 10 OFFSET 20`

```python
from sqlglot import parse_one, Dialects

sql = "SELECT * FROM data LIMIT 10, 20"

print(parse_one(sql, read=Dialects.CLICKHOUSE))
```

We got the such error:
```
sqlglot.errors.ParseError: Expected table name. Line 2, Col: 30.
  
SELECT * FROM data LIMIT 10, 20
```

Can we try to support it?


Discussion:

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -1513,7 +1513,7 @@ def _parse_limit(self, this=None, top=False):
         return this
 
     def _parse_offset(self, this=None):
-        if not self._match(TokenType.OFFSET):
+        if not self._match_set((TokenType.OFFSET, TokenType.COMMA)):
             return this
         count = self._parse_number()
         self._match_set((TokenType.ROW, TokenType.ROWS))


Test patch:
diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -989,6 +989,7 @@ def test_operators(self):
         )
 
     def test_limit(self):
+        self.validate_all("SELECT * FROM data LIMIT 10, 20", write={"sqlite": "SELECT * FROM data LIMIT 10 OFFSET 20"})
         self.validate_all(
             "SELECT x FROM y LIMIT 10",
             write={
Repository: tobymao/sqlglot

Issue:
DELETE USING + alias not supported
Following up on https://github.com/tobymao/sqlglot/issues/594 (thanks by the way!):

The parser fails with:
```
sqlglot.errors.ParseError: Invalid expression / Unexpected token. Line 1, Col: 31.
```
when parsing
```sql
delete from event using sales as s where event.eventid=s.eventid;
```
I verified that using an alias is allowed by executing the following:
```sql
create TEMPORARY table event (eventid int);
create TEMPORARY table sales (eventid int);
delete from event using sales as s where event.eventid=s.eventid;
```
in Redshift.


Discussion:
Oops, I think I made a mistake there in the call to parse table. Fixing it right now.

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -999,9 +999,7 @@ def _parse_delete(self):
         return self.expression(
             exp.Delete,
             this=self._parse_table(schema=True),
-            using=self._parse_csv(
-                lambda: self._match(TokenType.USING) and self._parse_table(schema=True)
-            ),
+            using=self._parse_csv(lambda: self._match(TokenType.USING) and self._parse_table()),
             where=self._parse_where(),
         )
 


Test patch:
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -507,6 +507,7 @@ DELETE FROM x WHERE y > 1
 DELETE FROM y
 DELETE FROM event USING sales WHERE event.eventid = sales.eventid
 DELETE FROM event USING sales, USING bla WHERE event.eventid = sales.eventid
+DELETE FROM event USING sales AS s WHERE event.eventid = s.eventid
 PREPARE statement
 EXECUTE statement
 DROP TABLE a
Repository: tobymao/sqlglot

Issue:
DuckDB `array_length(..., 1)` fails to parse
```
In [4]: import sqlglot as sg

In [5]: sg.__version__
Out[5]: '10.1.0'

In [6]: sg.parse_one('select array_length([0], 1) as x', read='duckdb')
ParseError: The number of provided arguments (2) is greater than the maximum number of supported arguments (1). Line 1, Col: 27.
  select array_length([0], 1) as x
```

DuckDB allows the second argument (dimension) for compatibility with postgres:

```
❯ duckdb <<< "select array_length([0], 1) as x"
┌───────┐
│   x   │
│ int64 │
├───────┤
│     1 │
└───────┘
```


Discussion:

Resolving patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -2447,7 +2447,7 @@ class ArrayFilter(Func):
 
 
 class ArraySize(Func):
-    pass
+    arg_types = {"this": True, "expression": False}
 
 
 class ArraySort(Func):


Test patch:
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -105,6 +105,10 @@ def test_duckdb(self):
                 "spark": "ARRAY(0, 1, 2)",
             },
         )
+        self.validate_all(
+            "SELECT ARRAY_LENGTH([0], 1) AS x",
+            write={"duckdb": "SELECT ARRAY_LENGTH(LIST_VALUE(0), 1) AS x"},
+        )
         self.validate_all(
             "REGEXP_MATCHES(x, y)",
             write={
Repository: tobymao/sqlglot

Issue:
Redshift DECODE
Current parsing for Redshift DECODE leads to a parsing error: https://docs.aws.amazon.com/redshift/latest/dg/r_DECODE_expression.html
e.g. SELECT DECODE(COL1, 'replace_this', 'with_this', 'replace_that', 'with_that') 

Redshift DECODE is essentially REPLACE but allows unlimited arguments. 

However, mapping DECODE to REPLACE in the tokenizer didn't work and I realised this was the wrong approach. I then tried adding DECODE to FUNC_TOKENS in redshift.py but that still didn't work. Not sure how to override DECODE in expressions.


Discussion:

Resolving patch:
diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py
--- a/sqlglot/dialects/redshift.py
+++ b/sqlglot/dialects/redshift.py
@@ -1,6 +1,7 @@
 from __future__ import annotations
 
 from sqlglot import exp, transforms
+from sqlglot.dialects.dialect import rename_func
 from sqlglot.dialects.postgres import Postgres
 from sqlglot.tokens import TokenType
 
@@ -13,6 +14,12 @@ class Redshift(Postgres):
         "HH": "%H",
     }
 
+    class Parser(Postgres.Parser):
+        FUNCTIONS = {
+            **Postgres.Parser.FUNCTIONS,  # type: ignore
+            "DECODE": exp.Matches.from_arg_list,
+        }
+
     class Tokenizer(Postgres.Tokenizer):
         ESCAPES = ["\\"]
 
@@ -50,4 +57,5 @@ class Generator(Postgres.Generator):
             exp.DistKeyProperty: lambda self, e: f"DISTKEY({e.name})",
             exp.SortKeyProperty: lambda self, e: f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})",
             exp.DistStyleProperty: lambda self, e: self.naked_property(e),
+            exp.Matches: rename_func("DECODE"),
         }


Test patch:
diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py
--- a/tests/dialects/test_redshift.py
+++ b/tests/dialects/test_redshift.py
@@ -56,8 +56,19 @@ def test_redshift(self):
                 "redshift": 'SELECT a, b FROM (SELECT a, b, ROW_NUMBER() OVER (PARTITION BY a ORDER BY c DESC) AS "_row_number" FROM x) WHERE "_row_number" = 1',
             },
         )
+        self.validate_all(
+            "DECODE(x, a, b, c, d)",
+            write={
+                "": "MATCHES(x, a, b, c, d)",
+                "oracle": "DECODE(x, a, b, c, d)",
+                "snowflake": "DECODE(x, a, b, c, d)",
+            },
+        )
 
     def test_identity(self):
+        self.validate_identity(
+            "SELECT DECODE(COL1, 'replace_this', 'with_this', 'replace_that', 'with_that')"
+        )
         self.validate_identity("CAST('bla' AS SUPER)")
         self.validate_identity("CREATE TABLE real1 (realcol REAL)")
         self.validate_identity("CAST('foo' AS HLLSKETCH)")
Repository: tobymao/sqlglot

Issue:
Functions transpiled incorrectly from MySQL to BigQuery
```python
import sqlglot
print(sqlglot.transpile("SELECT 'foo' regexp '.*';", read="mysql", write="bigquery"))
```
This currently transpiles to `SELECT REGEXP_LIKE('foo', '.*')` which is not valid for BigQuery (I guess the correct function would be `REGEXP_CONTAINS`).

Overall, how robust should I expect transpilation to be? Are certain language pairs better supported than others? Are functions more problematic than other constructs?


Discussion:
transpilation is most robust in presto -> spark -> duckdb. these dialects are used in production systems at companies i've worked at.

adding compatability is easy, and if you have a particularly pair that you care about, the architecture allows for integration to be pretty simple

Resolving patch:
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -110,17 +110,17 @@ class Tokenizer(tokens.Tokenizer):
 
         KEYWORDS = {
             **tokens.Tokenizer.KEYWORDS,
+            "BEGIN": TokenType.COMMAND,
+            "BEGIN TRANSACTION": TokenType.BEGIN,
             "CURRENT_DATETIME": TokenType.CURRENT_DATETIME,
             "CURRENT_TIME": TokenType.CURRENT_TIME,
             "GEOGRAPHY": TokenType.GEOGRAPHY,
-            "INT64": TokenType.BIGINT,
             "FLOAT64": TokenType.DOUBLE,
+            "INT64": TokenType.BIGINT,
+            "NOT DETERMINISTIC": TokenType.VOLATILE,
             "QUALIFY": TokenType.QUALIFY,
             "UNKNOWN": TokenType.NULL,
             "WINDOW": TokenType.WINDOW,
-            "NOT DETERMINISTIC": TokenType.VOLATILE,
-            "BEGIN": TokenType.COMMAND,
-            "BEGIN TRANSACTION": TokenType.BEGIN,
         }
         KEYWORDS.pop("DIV")
 
@@ -131,6 +131,7 @@ class Parser(parser.Parser):
             "DATE_ADD": _date_add(exp.DateAdd),
             "DATETIME_ADD": _date_add(exp.DatetimeAdd),
             "DIV": lambda args: exp.IntDiv(this=seq_get(args, 0), expression=seq_get(args, 1)),
+            "REGEXP_CONTAINS": exp.RegexpLike.from_arg_list,
             "TIME_ADD": _date_add(exp.TimeAdd),
             "TIMESTAMP_ADD": _date_add(exp.TimestampAdd),
             "DATE_SUB": _date_add(exp.DateSub),
@@ -183,6 +184,7 @@ class Generator(generator.Generator):
             exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC"
             if e.name == "IMMUTABLE"
             else "NOT DETERMINISTIC",
+            exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
         }
 
         TYPE_MAPPING = {


Test patch:
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -6,6 +6,11 @@ class TestBigQuery(Validator):
     dialect = "bigquery"
 
     def test_bigquery(self):
+        self.validate_all(
+            "REGEXP_CONTAINS('foo', '.*')",
+            read={"bigquery": "REGEXP_CONTAINS('foo', '.*')"},
+            write={"mysql": "REGEXP_LIKE('foo', '.*')"},
+        ),
         self.validate_all(
             '"""x"""',
             write={
Repository: tobymao/sqlglot

Issue:
[BigQuery] Parser does not support extract(WEEK(<WEEKDAY>) ...) syntax
BigQuery supports code like 

```sql
select extract(week(monday) from created_at) as week_created_at from my_table
```

to let users choose which day weeks start on.

Documentation at https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#extract

When trying to use `sqlglot.parse_one(query, read='bigquery')`, sqlglot throws the error: `sqlglot.errors.ParseError: Expected FROM or comma after EXTRACT.`


Discussion:

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -2241,7 +2241,7 @@ def _parse_if(self):
         return self._parse_window(this)
 
     def _parse_extract(self):
-        this = self._parse_var() or self._parse_type()
+        this = self._parse_function() or self._parse_var() or self._parse_type()
 
         if self._match(TokenType.FROM):
             return self.expression(exp.Extract, this=this, expression=self._parse_bitwise())


Test patch:
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -75,6 +75,7 @@ ARRAY(1, 2)
 ARRAY_CONTAINS(x, 1)
 EXTRACT(x FROM y)
 EXTRACT(DATE FROM y)
+EXTRACT(WEEK(monday) FROM created_at)
 CONCAT_WS('-', 'a', 'b')
 CONCAT_WS('-', 'a', 'b', 'c')
 POSEXPLODE("x") AS ("a", "b")
Repository: tobymao/sqlglot

Issue:
Column constraint order broken
Column constraint don't have to be in a specific order in a create table statement.

In the current version 10.2.9 the following sql results in

``create table t2(n int not null default 0)`` -> ``CREATE TABLE t2 (n INT NOT NULL DEFAULT 0)``

which is correct.

However this one is broken:

``create table t2(n int default 0 not null)`` -> ``CREATE TABLE t2 (n INT DEFAULT NOT 0 NULL)``

Notice the **DEFAULT NOT 0 NULL** part, which is invalid SQL.

In sqlglot version 10.0.0 the result was still correct ``CREATE TABLE t2 (n INT DEFAULT 0 NOT NULL)``, so a change between 10.0.0 and the current version must have introduced this.


Discussion:

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -2120,7 +2120,7 @@ def _parse_column_constraint(self):
         elif self._match(TokenType.ENCODE):
             kind = self.expression(exp.EncodeColumnConstraint, this=self._parse_var())
         elif self._match(TokenType.DEFAULT):
-            kind = self.expression(exp.DefaultColumnConstraint, this=self._parse_conjunction())
+            kind = self.expression(exp.DefaultColumnConstraint, this=self._parse_bitwise())
         elif self._match_pair(TokenType.NOT, TokenType.NULL):
             kind = exp.NotNullColumnConstraint()
         elif self._match(TokenType.NULL):


Test patch:
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -460,6 +460,7 @@ CREATE TABLE z (end INT)
 CREATE TABLE z (a ARRAY<TEXT>, b MAP<TEXT, DOUBLE>, c DECIMAL(5, 3))
 CREATE TABLE z (a INT, b VARCHAR COMMENT 'z', c VARCHAR(100) COMMENT 'z', d DECIMAL(5, 3))
 CREATE TABLE z (a INT(11) DEFAULT UUID())
+CREATE TABLE z (n INT DEFAULT 0 NOT NULL)
 CREATE TABLE z (a INT(11) DEFAULT NULL COMMENT '客户id')
 CREATE TABLE z (a INT(11) NOT NULL DEFAULT 1)
 CREATE TABLE z (a INT(11) NOT NULL DEFAULT -1)
Repository: tobymao/sqlglot

Issue:
BUG: can not parse presto sql
Hi

Below is valid presto sql which sqlglot can not parse. Can you please fix it.

```
WITH
    A(filter) AS (
        VALUES 1, 2, 3
    )

SELECT
    *
FROM
    A
WHERE
    filter >= 2
```



Discussion:

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -169,6 +169,7 @@ class Parser(metaclass=_Parser):
         TokenType.ESCAPE,
         TokenType.FALSE,
         TokenType.FIRST,
+        TokenType.FILTER,
         TokenType.FOLLOWING,
         TokenType.FORMAT,
         TokenType.FUNCTION,
@@ -1155,9 +1156,19 @@ def _parse_select(self, nested=False, table=False):
             self._match_r_paren()
             this = self._parse_subquery(this)
         elif self._match(TokenType.VALUES):
+            if self._curr.token_type == TokenType.L_PAREN:
+                # We don't consume the left paren because it's consumed in _parse_value
+                expressions = self._parse_csv(self._parse_value)
+            else:
+                # In presto we can have VALUES 1, 2 which results in 1 column & 2 rows.
+                # Source: https://prestodb.io/docs/current/sql/values.html
+                expressions = self._parse_csv(
+                    lambda: self.expression(exp.Tuple, expressions=[self._parse_conjunction()])
+                )
+
             this = self.expression(
                 exp.Values,
-                expressions=self._parse_csv(self._parse_value),
+                expressions=expressions,
                 alias=self._parse_table_alias(),
             )
         else:


Test patch:
diff --git a/tests/test_transpile.py b/tests/test_transpile.py
--- a/tests/test_transpile.py
+++ b/tests/test_transpile.py
@@ -28,7 +28,7 @@ def test_alias(self):
         self.assertEqual(transpile("SELECT 1 current_datetime")[0], "SELECT 1 AS current_datetime")
         self.assertEqual(transpile("SELECT 1 row")[0], "SELECT 1 AS row")
 
-        for key in ("union", "filter", "over", "from", "join"):
+        for key in ("union", "over", "from", "join"):
             with self.subTest(f"alias {key}"):
                 self.validate(f"SELECT x AS {key}", f"SELECT x AS {key}")
                 self.validate(f'SELECT x "{key}"', f'SELECT x AS "{key}"')
@@ -263,6 +263,10 @@ def test_with(self):
             "WITH a AS (SELECT 1), WITH b AS (SELECT 2) SELECT *",
             "WITH a AS (SELECT 1), b AS (SELECT 2) SELECT *",
         )
+        self.validate(
+            "WITH A(filter) AS (VALUES 1, 2, 3) SELECT * FROM A WHERE filter >= 2",
+            "WITH A(filter) AS (VALUES (1), (2), (3)) SELECT * FROM A WHERE filter >= 2",
+        )
 
     def test_time(self):
         self.validate("TIMESTAMP '2020-01-01'", "CAST('2020-01-01' AS TIMESTAMP)")
Repository: tobymao/sqlglot

Issue:
Using reserved words as identifiers
In Bigquery, various reserved words and builtin function names can be used as unquoted identifiers.

E.g. `WITH view AS (SELECT 1 AS x) SELECT * FROM view` is valid in BQ but raises a ParseError "Expected CTE to have alias".  Renaming the CTE to something else stops the error.

Another example is `WITH q AS (SELECT 'A' as a, 51 as b, 23 as c UNION ALL SELECT 'B', 77, 0) SELECT * FROM q UNPIVOT(values FOR quarter IN (b, c))` which fails with ParseError "Expecting FOR" because the unpivot of `values`; another identifier parses ok.

Another example is `SELECT CAST(time*1000 AS INT64) FROM (SELECT 0.1 AS time)` where `time` is used as a column name; sqlglot raises ParseError "Expected AS after CAST".  Naming the column something else stops the error.


Discussion:
I'll take a look. I think you just need to add the tokens of interest to `ID_VAR_TOKENS` for this to be resolved.

Resolving patch:
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -165,6 +165,11 @@ class Parser(parser.Parser):
             TokenType.TABLE,
         }
 
+        ID_VAR_TOKENS = {
+            *parser.Parser.ID_VAR_TOKENS,  # type: ignore
+            TokenType.VALUES,
+        }
+
     class Generator(generator.Generator):
         TRANSFORMS = {
             **generator.Generator.TRANSFORMS,  # type: ignore
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -233,6 +233,7 @@ class Parser(metaclass=_Parser):
         TokenType.UNPIVOT,
         TokenType.PROPERTIES,
         TokenType.PROCEDURE,
+        TokenType.VIEW,
         TokenType.VOLATILE,
         TokenType.WINDOW,
         *SUBQUERY_PREDICATES,


Test patch:
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -6,6 +6,7 @@ class TestBigQuery(Validator):
     dialect = "bigquery"
 
     def test_bigquery(self):
+        self.validate_identity("SELECT * FROM q UNPIVOT(values FOR quarter IN (b, c))")
         self.validate_all(
             "REGEXP_CONTAINS('foo', '.*')",
             read={"bigquery": "REGEXP_CONTAINS('foo', '.*')"},
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -643,3 +643,4 @@ ALTER TABLE integers ALTER COLUMN i DROP DEFAULT
 ALTER TABLE mydataset.mytable DROP COLUMN A, DROP COLUMN IF EXISTS B
 ALTER TABLE mydataset.mytable ADD COLUMN A TEXT, ADD COLUMN IF NOT EXISTS B INT
 SELECT div.a FROM test_table AS div
+WITH view AS (SELECT 1 AS x) SELECT * FROM view
Repository: tobymao/sqlglot

Issue:
Support for Merge
Hi there!

I have a t-sql merge statement:

```sql
MERGE [CORE].[DIM_BusinessUnit] a
			USING [TRANSF].[Merge_BusinessUnit] b
			             ON a.[IdDWH] = b.[IdDWH]
			
			WHEN MATCHED AND EXISTS
			(
				SELECT a.[Name]
					   
				EXCEPT
			        
				SELECT b.[Name]
			
			)
			THEN 
			UPDATE SET     a.[Name]			 =  b.[Name]
						  ;
```

seems to be unparseable

Enough issues for a while now ;) sqlglot is great and already helping me a lot


Discussion:
Thanks for the reports, I'll take a look soon. I'm currently tackling the UDF issue, which required a handful of additions in the end

Resolving patch:
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -3076,7 +3076,7 @@ def _parse_set_item(self) -> t.Optional[exp.Expression]:
 
     def _parse_merge(self) -> exp.Expression:
         self._match(TokenType.INTO)
-        target = self._parse_table(schema=True)
+        target = self._parse_table()
 
         self._match(TokenType.USING)
         using = self._parse_table()


Test patch:
diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -1365,3 +1365,19 @@ def test_merge(self):
                 "spark": "MERGE INTO target USING source ON target.id = source.id WHEN MATCHED THEN UPDATE * WHEN NOT MATCHED THEN INSERT *",
             },
         )
+        self.validate_all(
+            """
+            MERGE a b USING c d ON b.id = d.id
+            WHEN MATCHED AND EXISTS (
+                SELECT b.name
+                EXCEPT
+                SELECT d.name
+            )
+            THEN UPDATE SET b.name = d.name
+            """,
+            write={
+                "bigquery": "MERGE INTO a AS b USING c AS d ON b.id = d.id WHEN MATCHED AND EXISTS(SELECT b.name EXCEPT DISTINCT SELECT d.name) THEN UPDATE SET b.name = d.name",
+                "snowflake": "MERGE INTO a AS b USING c AS d ON b.id = d.id WHEN MATCHED AND EXISTS(SELECT b.name EXCEPT SELECT d.name) THEN UPDATE SET b.name = d.name",
+                "spark": "MERGE INTO a AS b USING c AS d ON b.id = d.id WHEN MATCHED AND EXISTS(SELECT b.name EXCEPT SELECT d.name) THEN UPDATE SET b.name = d.name",
+            },
+        )