根据条件创建 SQL 个视图

Create SQL view based on condition

我想弄清楚如何从 table 创建一个 sql 视图,其中一列包含字符串和 json 格式(它有 varchar 作为数据类型)。某些行中的列仅包含字符 (e.g.32564 ),而其他行中的列包含 json 数据。我如何根据此列创建 视图 ,如果 column1 中存储了 json,则:

create view dbo.vTable1
select 
...
from dbo.Table1
cross apply openjson(...) with (...)
cross apply openjson(...) with (...)

否则:

create view dbo.vTable2
select 
...
from dbo.Table1

(我不想使用存储过程)

这是根据评论整理的解决方案。

示例数据

create table data
(
  id int,
  value nvarchar(100)
);

insert into data (id, value) values
(1,
'{
  "Key1": 100,
  "Key2": "One hundred"
}'),
(2,
'{
  "Key1": 200,
  "Key2": "Two hundred"
}'),
(3, '300'),
(4, '400'),
(5, 'Five hundred'),
(6, 'Six hundred');

解决方案 1

如果你想return数值数据。

create view idNumberView as
select d.id,
       jv.result
from data d
cross apply openjson(d.value) with (result int '$."Key1"') jv
where isjson(d.value) = 1
  union all
select d.id,
       convert(int, d.value)
from data d
where try_convert(int, d.value) is not null;

结果 1

id  result
--  ------
1   100
2   200
3   300
4   400

解决方案 2

如果你想return字符串数据。

create view idStringView as
select d.id,
       jv.result
from data d
cross apply openjson(d.value) with (result nvarchar(20) '$."Key2"') jv
where isjson(d.value) = 1
  union all
select d.id,
       d.value
from data d
where try_convert(int, d.value) is null
  and isjson(d.value) = 0;

结果 2

id  result
--  ------------
1   One hundred
2   Two hundred
5   Five hundred
6   Six hundred

Fiddle 查看两种解决方案的实际应用。